package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.DateTimeUtils;
import com.ybkj.daijia.InfoFeeType;
import com.ybkj.daijia.OrderNumberConfig;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.cache.MyCacheManager;
import com.ybkj.daijia.chart.TableOrderMonthVo;
import com.ybkj.daijia.common.CompanyOrderVo;
import com.ybkj.daijia.common.DriverOrderDetailVo;
import com.ybkj.daijia.common.DriverOrderVo;
import com.ybkj.daijia.common.HtmlHelper;
import com.ybkj.daijia.common.MemberOrderVo;
import com.ybkj.daijia.common.OrderFromSourceVo;
import com.ybkj.daijia.common.PageVo;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.config.ZhuanApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.OrderRevokeTimerTask;
import com.ybkj.daijia.server.errand.SelectPrice;
import com.ybkj.daijia.server.event.common.event.IntroduceRebateEvent;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.MemberConsumedEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderCancelEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderFinishEvent;
import com.ybkj.daijia.server.mapper.AreaMapper;
import com.ybkj.daijia.server.mapper.CompanyMapper;
import com.ybkj.daijia.server.mapper.DriverChoseLevelCarMapper;
import com.ybkj.daijia.server.mapper.DriverLevelDetailMapper;
import com.ybkj.daijia.server.mapper.DriverLevelMapper;
import com.ybkj.daijia.server.mapper.DriverLevelMoneyTimeDetailMapper;
import com.ybkj.daijia.server.mapper.DriverMapper;
import com.ybkj.daijia.server.mapper.DriverPaymentsRecordMapper;
import com.ybkj.daijia.server.mapper.FinancialRecordMapper;
import com.ybkj.daijia.server.mapper.FirstOrderPassengerMapper;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.mc.PassengerAddress;
import com.ybkj.daijia.server.mc.PassengerConcats;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.ChargeStartDistance;
import com.ybkj.daijia.server.model.ChargeStartTime;
import com.ybkj.daijia.server.model.ChartDay;
import com.ybkj.daijia.server.model.ChartMonth;
import com.ybkj.daijia.server.model.ChartYear;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverChoseLevelCar;
import com.ybkj.daijia.server.model.DriverLevel;
import com.ybkj.daijia.server.model.DriverLevel.TimePoint;
import com.ybkj.daijia.server.model.DriverLevelDetail;
import com.ybkj.daijia.server.model.DriverLevelDetail.DriverLevelType;
import com.ybkj.daijia.server.model.DriverLevelMoneyDetail;
import com.ybkj.daijia.server.model.DriverLevelMoneyDetail.DriverLevelMoneyType;
import com.ybkj.daijia.server.model.DriverLevelMoneyTimeDetail;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.model.FinancialRecord;
import com.ybkj.daijia.server.model.FirstOrderPassenger;
import com.ybkj.daijia.server.model.HelpPayRecord;
import com.ybkj.daijia.server.model.Rate;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.Activity.OrderType;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.DriverHelppayService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SuperviceService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.sp.ClbxMessage;
import com.ybkj.daijia.server.zhuan.Car;
import com.ybkj.daijia.server.zhuan.CarType;
import com.ybkj.daijia.server.zhuan.CarTypeCompany;
import com.ybkj.daijia.server.zhuan.CarTypeRel;
import com.ybkj.daijia.server.zhuan.Insurance;
import com.ybkj.daijia.server.zhuan.Order;
import com.ybkj.daijia.server.zhuan.Order.PayTypeDetails;
import com.ybkj.daijia.server.zhuan.OrderMemo;
import com.ybkj.daijia.server.zhuan.OrderOrbit;
import com.ybkj.daijia.server.zhuan.OrderReview;
import com.ybkj.daijia.server.zhuan.OrderStatus;
import com.ybkj.daijia.server.zhuan.OrderTemp;
import com.ybkj.daijia.server.zhuan.PayRecordOrder;
import com.ybkj.daijia.server.zhuan.ServiceType;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.serverUtils.UseAllDataUtil;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;

@Service
public class DefaultZhuancheService implements ZhuancheService {

    private static final Logger logger = LoggerFactory.getLogger(DefaultZhuancheService.class);

    @Autowired
    private SuperviceService superviceService;

    @Autowired
    private ZhuanApi zhuanApi;
    @Autowired
    private SalesApi salesApi;
    @Autowired
    private PassengerApi passengerApi;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private DriverLevelMapper driverLevelMapper;
    @Autowired
    private DriverChoseLevelCarMapper driverChoseLevelCarMapper;
    @Autowired
    private DriverLevelDetailMapper driverLevelDetailMapper;
    @Autowired
    private DriverLevelMoneyTimeDetailMapper driverLevelMoneyTimeDetailMapper;

    @Autowired
    private FinancialRecordMapper financialRecordMapper;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private FirstOrderPassengerMapper firstOrderPassengerMapper;
    @Autowired
    private DriverPaymentsRecordMapper driverPaymentsRecordMapper;
    @Autowired
    private SmsService smsService;
    @Autowired
    private MyCacheManager cacheManager;
    @Autowired
    private DriverHelppayService helppayService;

    // 预算价格
    @Override
    public Map<String, Object> getPrice(Long areaId, Long distance, Long time) {
        Map<String, Object> map = new HashMap<String, Object>();
        Area area = areaMapper.selectByPrimaryKeyWithCharge(areaId);
        if (area != null) {
            long travelTime = 0;
            Double mileage = 0.0;
            if (time != null) {
                travelTime = time / 60;
            }
            if (distance != null) {
                mileage = Double.valueOf(distance / 1000);
            }
            BigDecimal money = BigDecimal.ZERO;
            SelectPrice selectPrice = new SelectPrice();
            selectPrice.setPrice(travelTime, mileage, area, null, 0D);
            money = selectPrice.shouldCash;
            BigDecimal startPrice = selectPrice.qbCost;
            BigDecimal mileagePrice = selectPrice.disCost;
            BigDecimal travelTimePrice = selectPrice.travalTimeCost;
            ChargeStartTime price = selectPrice.getPrice();
            StringBuilder builder = new StringBuilder();
            builder.append("起步价:" + startPrice + "元\n");
            List<ChargeStartDistance> distances = price.getChargeStartDistances();

            if (distances != null && distances.size() != 0) {
                for (ChargeStartDistance d : distances) {
                    builder.append(d.getStartdistance() + "公里到" + d.getDistance() + "公里内,加收" + d.getMoney() + "元");
                    builder.append("\n");
                }
            }

            builder.append("超过" + price.getQblc() + "公里");
            builder.append("以后每" + price.getDjglUnit() + "公里");
            builder.append("加收" + price.getDjglCost() + "元");
            if (price.getDjglThresholdt() != 0) {
                builder.append("(不足" + price.getDjglThresholdt() + "公里不计费)");
            }
            builder.append("\n");
            builder.append("起步后" + price.getQbsj() + "分钟内不收费");
            builder.append("以后每" + price.getDjsjUnit() + "分钟");
            builder.append("加收" + price.getDjsjCost() + "元");
            if (price.getDjsjThresholdt() != 0) {
                builder.append("(不足" + price.getDjsjThresholdt() + "分钟不收费)");
            }
            builder.append("\n");
            builder.append("免费等候" + price.getMfdhsj() + "分钟");
            BigDecimal bigDecimal = price.getDhsjAtonceCost();

            if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
                builder.append("到达则立即加收" + price.getDhsjAtonceCost() + "元");
            }
            builder.append("后每" + price.getDhsjUnit() + "分钟");
            builder.append("加收" + price.getDhsjCost() + "元");
            if (price.getDhsjThresholdt() != 0) {
                builder.append("(低于" + price.getDhsjThresholdt() + "分钟不计费)");
            }
            builder.append("\n");
            if (StringUtils.isNotBlank(area.getMemo())) {
                builder.append("备注:" + area.getMemo());
            }
            String pay_detail = builder.toString();
            map.put("success", true);
            map.put("message", "请求成功");
            map.put("money", money != null ? money.doubleValue() : 0);
            map.put("travelTime", travelTime); // 执行时间 分钟
            map.put("startPrice", startPrice != null ? startPrice.doubleValue() : 0); // 起步价
            map.put("mileage", mileage); // 行驶里程 公里
            map.put("mileagePrice", mileagePrice != null ? mileagePrice.doubleValue() : 0); // 行驶里程费用
            map.put("travelTimePrice", travelTimePrice != null ? travelTimePrice.doubleValue() : 0); // 服务时间费用
            map.put("pay_detail", pay_detail);
        } else {
            map.put("success", false);
            map.put("message", "收费标准为空");
        }
        return map;
    }

    /**
     * 司机端获取价格
     *
     * @param areaId
     * @param distance
     * @param time
     * @return
     * @record zhyu
     */
    @Override
    public Map<String, Object> getNewPrice(Long areaId, Double distance, Long time) {

        Map<String, Object> map = new HashMap<String, Object>();
        Area area = areaMapper.selectByPrimaryKeyWithCharge(areaId);
        if (area != null) {

            com.ybkj.daijia.server.zhuan.SelectPrice selectPrice = new com.ybkj.daijia.server.zhuan.SelectPrice();
            selectPrice.computePrice(0, time * 60, 0L, distance, area, null);
            ChargeStartTime price = selectPrice.getPrice();
            StringBuilder builder = new StringBuilder();
            BigDecimal startPrice = price.getCost();
            builder.append("起步价:" + startPrice + "元\n");
            List<ChargeStartDistance> distances = price.getChargeStartDistances();

            if (distances != null && distances.size() != 0) {
                for (ChargeStartDistance d : distances) {
                    builder.append(d.getStartdistance() + "公里到" + d.getDistance() + "公里内,加收" + d.getMoney() + "元");
                    builder.append("\n");
                }
            }

            builder.append("超过" + price.getQblc() + "公里");
            builder.append("以后每" + price.getDjglUnit() + "公里");
            builder.append("加收" + price.getDjglCost() + "元");
            builder.append("\n");
            builder.append("起步后" + price.getQbsj() + "分钟内不收费");
            builder.append("以后每" + price.getDjsjUnit() + "分钟");
            builder.append("\n");
            builder.append("免费等候" + price.getMfdhsj() + "分钟");
            BigDecimal bigDecimal = price.getDhsjAtonceCost();

            builder.append("后每" + price.getDhsjUnit() + "分钟");
            builder.append("加收" + price.getDhsjCost() + "元");
            builder.append("\n");
            if (StringUtils.isNotBlank(area.getMemo())) {
                builder.append("备注:" + area.getMemo());
            }
            String pay_detail = builder.toString();
            map.put("success", true);
            map.put("message", "请求成功");
            map.put("money", selectPrice.getShouldCash());
            map.put("startPrice", startPrice != null ? startPrice.doubleValue() : 0); // 起步价
            map.put("mileagePrice", selectPrice.getDisCost()); // 行驶里程费用
            map.put("travelTimePrice", selectPrice.getTravalTimeCost()); // 服务时间费用
            map.put("remoteCost", selectPrice.getRemoteCost()); // 远程费用
            map.put("pay_detail", pay_detail);
        } else {
            map.put("success", false);
            map.put("message", "收费标准为空");
        }
        return map;
    }

    @Override
    public Page<Map<String, Object>> orderListData(String orderNo, String passengerPhone, String employPhone, String companyName,
        String createOrderName, String startTime, String endTime, String allorderType, String allstatus, Integer page, Integer rows,
        String treatment, String startFinishTime, String endFinishTime) throws ParseException {
        // 分公司查询本公司数据
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDERS).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        kv.put("orderby", "status asc,created desc");
        builder.append("&orderby={orderby}");
        if (!principal.isCompanyType()) {// 不是主公司时默认传本公司Id
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            builder.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(orderNo)) {
            kv.put("orderNo", orderNo);
            builder.append("&orderNo={orderNo}");
        }
        if (StringUtils.isNotBlank(passengerPhone)) {
            kv.put("passengerName", passengerPhone);
            builder.append("&passengerName={passengerName}");
        }
        if (StringUtils.isNotBlank(employPhone)) {
            kv.put("employName", employPhone);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", companyName);
            builder.append("&companyName={companyName}");
        }
        if (StringUtils.isNotBlank(createOrderName)) {
            kv.put("createOrderName", createOrderName);
            builder.append("&createOrderName={createOrderName}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            Date start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            kv.put("startTime", String.valueOf(start.getTime()));
            builder.append("&startTime={startTime}");
        }
        if (StringUtils.isNotBlank(endTime)) {
            Date end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            kv.put("endTime", String.valueOf(end.getTime()));
            builder.append("&endTime={endTime}");
        }
        if (StringUtils.isNotBlank(startFinishTime)) {
            Date startFinish = DateUtils.parseDate(startFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("startFinishTime", String.valueOf(startFinish.getTime()));
            builder.append("&startFinishTime={startFinishTime}");
        }
        if (StringUtils.isNotBlank(endFinishTime)) {
            Date endFinish = DateUtils.parseDate(endFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("endFinishTime", String.valueOf(endFinish.getTime()));
            builder.append("&endFinishTime={endFinishTime}");
        }
        if (StringUtils.isNotBlank(allorderType)) {
            kv.put("allorderType", allorderType);
            builder.append("&allorderType={allorderType}");
        }
        if (StringUtils.isNotBlank(allstatus)) {
            kv.put("allstatus", allstatus);
            builder.append("&allstatus={allstatus}");
        }
        if ("true".equals(treatment)) {
            kv.put("treatment", String.valueOf(true));
            builder.append("&treatment={treatment}");
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        List<Order> list = new ArrayList<Order>();
        long total = 0;
        List<Map<String, Object>> content = new ArrayList<Map<String, Object>>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
            SimpleDateFormat format = new SimpleDateFormat("MM/dd HH:mm");

            for (Order order : list) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", order.getId());
                map.put("balanceMoney", order.getBalanceMoney());
                map.put("budgetPay", order.getBudgetPay());
                map.put("cancelCause", order.getCancelCause() != null ? order.getCancelCause() : "-");
                map.put("carId", order.getCarId());
                map.put("carNumber", order.getCarNumber() != null ? order.getCarNumber() : "-");
                map.put("carTypeId", order.getCarTypeId());
                map.put("carTypeName", order.getCarTypeName());
                map.put("channelName", order.getChannelName());
                map.put("createOrderName", order.getCreateOrderName());
                map.put("companyId", order.getCompanyId());
                map.put("companyName", order.getCompanyName());
                map.put("created", format.format(order.getCreated()));
                map.put("employCompanyId", order.getEmployCompanyId());
                map.put("employId", order.getEmployId());
                map.put("employName", order.getEmployName() != null ? order.getEmployName() : "-");
                map.put("employPhone", UseAllDataUtil.useAllDataDriver(order.getEmployPhone() != null ? order.getEmployPhone() : "-"));
                map.put("employProfit", order.getEmployProfit());
                map.put("endAddress", order.getEndAddress());
                map.put("endAddressDetail", order.getEndAddressDetail());
                map.put("endlat", order.getEndLat());
                map.put("endlng", order.getEndLng());
                map.put("mileage", order.getMileage());
                map.put("mileagePrice", order.getMileagePrice());
                map.put("runtime", order.getRunTime());
                map.put("midwayWait", order.getMidwayWait());
                map.put("realPay", order.getRealPay());
                map.put("preAndAfterPayType", order.getPreAndAfterPayType());
                map.put("budgetPay", order.getBudgetPay());
                map.put("orderNo", order.getOrderNo());
                map.put("passengerId", order.getPassengerId());
                map.put("passengerName", order.getPassengerName());
                map.put("passengerPhone", UseAllDataUtil.useAllData(order.getPassengerPhone()));
                map.put("justKilometres", order.getJustKilometres());
                map.put("justMoney", order.getJustMoney());
                if (null == order.getBookStatus()) {
                    map.put("bookStatus", 0);
                } else {
                    map.put("bookStatus", order.getBookStatus());
                }
                if (StringUtils.isNotBlank(order.getShowPhone())) {
                    map.put("showPhone", UseAllDataUtil.useAllData(order.getShowPhone()));
                } else {
                    map.put("showPhone", passengerPhone);
                }
                map.put("review", order.getReview());
                map.put("serverTime", format.format(order.getServerTime()));
                map.put("startAddress", order.getStartAddress());
                map.put("startAddressDetail", order.getStartAddressDetail());
                map.put("startLat", order.getStartLat());
                map.put("startLng", order.getStartLng());
                map.put("startPrice", order.getStartPrice());
                map.put("status", order.getStatus());
                map.put("guoluMoney", order.getGuoluMoney());
                map.put("yuanchengMoney", order.getYuanchengMoney());
                map.put("otherMoney", order.getOtherMoney());
                String serviceTypeStr = "立即用车";
                com.ybkj.daijia.server.zhuan.Order.ServiceType serviceType = order.getServiceType();
                Integer bookStatus = order.getBookStatus();
                if (null != serviceType && serviceType.compareTo(Order.ServiceType.tangzu) == 0) {
                    if (null != bookStatus && bookStatus == 1) {
                        serviceTypeStr = "预约用车";
                    } else {
                        serviceTypeStr = "立即用车";
                    }
                }
                if (null != serviceType && serviceType.compareTo(Order.ServiceType.rizu) == 0) {
                    if (null != bookStatus && bookStatus == 1) {
                        serviceTypeStr = "预约日租";
                    } else {
                        serviceTypeStr = "日租";
                    }
                }
                if (null != serviceType && serviceType.compareTo(Order.ServiceType.banrizu) == 0) {
                    if (null != bookStatus && bookStatus == 1) {
                        serviceTypeStr = "预约半日租";
                    } else {
                        serviceTypeStr = "半日租";
                    }
                }
                if (null != serviceType && serviceType.compareTo(Order.ServiceType.jieji) == 0) {
                    if (null != bookStatus && bookStatus == 1) {
                        serviceTypeStr = "预约接机";
                    } else {
                        serviceTypeStr = "立即接机";
                    }
                }
                if (null != serviceType && serviceType.compareTo(Order.ServiceType.songji) == 0) {
                    if (null != bookStatus && bookStatus == 1) {
                        serviceTypeStr = "预约送机";
                    } else {
                        serviceTypeStr = "立即送机";
                    }
                }
                if (null != serviceType && serviceType.compareTo(Order.ServiceType.jiezhan) == 0) {
                    if (null != bookStatus && bookStatus == 1) {
                        serviceTypeStr = "预约接站";
                    } else {
                        serviceTypeStr = "立即接站";
                    }
                }
                if (null != serviceType && serviceType.compareTo(Order.ServiceType.songzhan) == 0) {
                    if (null != bookStatus && bookStatus == 1) {
                        serviceTypeStr = "预约送站";
                    } else {
                        serviceTypeStr = "立即送站";
                    }
                }
                map.put("serviceType", serviceTypeStr);
                String orderMemo = "";
                if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {
                    List<OrderMemo> orderMemos = order.getOrderMemos();
                    for (int i = 0; i < orderMemos.size(); i++) {
                        orderMemo += ((i + 1) + ":");
                        orderMemo += (orderMemos.get(i).getMemo() + "\n");
                    }
                }
                map.put("orderMemo", orderMemo);
                String memoStr = "";
                if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {
                    List<OrderMemo> orderMemos = order.getOrderMemos();
                    for (int i = 0; i < orderMemos.size(); i++) {
                        if (StringUtils.isNotBlank(orderMemos.get(i).getMemo())) {
                            memoStr += (HtmlHelper.html2Text(orderMemos.get(i).getMemo()));
                        }
                    }
                }
                map.put("memoStr", memoStr);
                map.put("couponId", order.getCouponId());
                content.add(map);
            }
        }

        return new PageImpl<Map<String, Object>>(content, pageable, total);
    }

    @Override
    public List<Map<String, Object>> orderListDataExport(HttpSession session, String orderNo, String passengerPhone, String employPhone,
        String companyName, String createOrderName, String startTime, String endTime, String allorderType, String allstatus, String treatment,
        String startFinishTime, String endFinishTime) throws ParseException {
        // 分公司查询本公司数据
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDER_EXPORT).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("orderby", "status asc,created desc");
        builder.append("&orderby={orderby}");
        if (!principal.isCompanyType()) {// 不是主公司时默认传本公司Id
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            builder.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(orderNo)) {
            kv.put("orderNo", orderNo);
            builder.append("&orderNo={orderNo}");
        }
        if (StringUtils.isNotBlank(passengerPhone)) {
            kv.put("passengerName", passengerPhone);
            builder.append("&passengerName={passengerName}");
        }
        if (StringUtils.isNotBlank(employPhone)) {
            kv.put("employName", employPhone);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", companyName);
            builder.append("&companyName={companyName}");
        }
        if (StringUtils.isNotBlank(createOrderName)) {
            kv.put("createOrderName", createOrderName);
            builder.append("&createOrderName={createOrderName}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            Date start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            kv.put("startTime", String.valueOf(start.getTime()));
            builder.append("&startTime={startTime}");
        }
        if (StringUtils.isNotBlank(endTime)) {
            Date end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            kv.put("endTime", String.valueOf(end.getTime()));
            builder.append("&endTime={endTime}");
        }
        if (StringUtils.isNotBlank(startFinishTime)) {
            Date startFinish = DateUtils.parseDate(startFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("startFinishTime", String.valueOf(startFinish.getTime()));
            builder.append("&startFinishTime={startFinishTime}");
        }
        if (StringUtils.isNotBlank(endFinishTime)) {
            Date endFinish = DateUtils.parseDate(endFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("endFinishTime", String.valueOf(endFinish.getTime()));
            builder.append("&endFinishTime={endFinishTime}");
        }
        if (StringUtils.isNotBlank(allorderType)) {
            kv.put("allorderType", allorderType);
            builder.append("&allorderType={allorderType}");
        }
        if (StringUtils.isNotBlank(allstatus)) {
            kv.put("allstatus", allstatus);
            builder.append("&allstatus={allstatus}");
        }
        if ("true".equals(treatment)) {
            kv.put("treatment", String.valueOf(true));
            builder.append("&treatment={treatment}");
        }
        builder.append("&page={page}");
        builder.append("&rows={rows}");

        Integer rows = 50;
        Integer currentRows = 0;
        Integer page = 0;

        kv.put("page", String.valueOf(page + 1));
        kv.put("rows", String.valueOf(rows));

        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        List<Map<String, Object>> content = new ArrayList<Map<String, Object>>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {

                Long total = 0L;
                List<Order> list = new ArrayList<Order>();
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());

                // 进度
                int totalPage = (int) (total / rows);
                if (total % rows != 0) {
                    totalPage++;
                }
                if (null != session.getAttribute("exportZhuancheProcess")) {
                    session.removeAttribute("exportZhuancheProcess");
                }
                session.setAttribute("exportZhuancheProcess", Double.valueOf(page + 1) / Double.valueOf(totalPage));
                // 进度

                if (total > 0) {
                    currentRows += rows;
                    page++;
                    while (currentRows < total) {
                        kv.put("page", String.valueOf(page + 1));
                        kv.put("rows", String.valueOf(rows));
                        String result2 = zhuanApi.get(builder.toString(), kv, settingUtils.get());
                        if (null != result2) {
                            JSONObject jo2 = new JSONObject(result2);
                            Integer code2 = jo2.getInt("code");
                            if (code2 == 0) {
                                Long total2 = 0L;
                                List<Order> list2 = new ArrayList<Order>();
                                JSONObject data2 = jo2.getJSONObject("data");
                                total2 = data.getLong("total");
                                JSONArray ja2 = data2.getJSONArray("rows");
                                list2 = gson.fromJson(ja2.toString(), new TypeToken<List<Order>>() {
                                }.getType());
                                if (total2 > 0) {
                                    list.addAll(list2);
                                }
                            }
                        }
                        currentRows += rows;
                        page++;
                        // 进度
                        session.setAttribute("exportZhuancheProcess", Double.valueOf(page + 1) / Double.valueOf(totalPage));
                        // 进度
                    }

                    SimpleDateFormat format = new SimpleDateFormat("MM/dd HH:mm");

                    for (Order order : list) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", order.getId());
                        map.put("balanceMoney", order.getBalanceMoney());
                        map.put("budgetPay", order.getBudgetPay());
                        map.put("cancelCause", order.getCancelCause() != null ? order.getCancelCause() : "-");
                        map.put("carId", order.getCarId());
                        map.put("carNumber", order.getCarNumber() != null ? order.getCarNumber() : "-");
                        map.put("carTypeId", order.getCarTypeId());
                        map.put("carTypeName", order.getCarTypeName());
                        map.put("channelName", order.getChannelName());
                        map.put("createOrderName", order.getCreateOrderName());
                        map.put("companyId", order.getCompanyId());
                        map.put("companyName", order.getCompanyName());
                        map.put("created", format.format(order.getCreated()));
                        map.put("employCompanyId", order.getEmployCompanyId());
                        map.put("employId", order.getEmployId());
                        map.put("employName", order.getEmployName() != null ? order.getEmployName() : "-");
                        map.put("employPhone", UseAllDataUtil.useAllData(order.getEmployPhone() != null ? order.getEmployPhone() : "-"));
                        map.put("employProfit", order.getEmployProfit());
                        map.put("endAddress", order.getEndAddress());
                        map.put("endAddressDetail", order.getEndAddressDetail());
                        map.put("endlat", order.getEndLat());
                        map.put("endlng", order.getEndLng());
                        map.put("mileage", order.getMileage());
                        map.put("mileagePrice", order.getMileagePrice());
                        map.put("runtime", order.getRunTime());
                        map.put("midwayWait", order.getMidwayWait());
                        map.put("midwayWait", order.getMidwayWait());
                        map.put("realPay", order.getRealPay());
                        map.put("preAndAfterPayType", order.getPreAndAfterPayType());
                        map.put("budgetPay", order.getBudgetPay());
                        map.put("orderNo", order.getOrderNo());
                        map.put("passengerId", order.getPassengerId());
                        map.put("passengerName", order.getPassengerName());
                        map.put("passengerPhone", UseAllDataUtil.useAllData(order.getPassengerPhone()));
                        map.put("justKilometres", order.getJustKilometres());
                        map.put("justMoney", order.getJustMoney());

                        if (StringUtils.isNotBlank(order.getShowPhone())) {
                            map.put("showPhone", UseAllDataUtil.useAllData(order.getShowPhone()));
                        } else {
                            map.put("showPhone", passengerPhone);
                        }

                        map.put("review", order.getReview());
                        map.put("serverTime", format.format(order.getServerTime()));
                        map.put("startAddress", order.getStartAddress());
                        map.put("startAddressDetail", order.getStartAddressDetail());
                        map.put("startLat", order.getStartLat());
                        map.put("startLng", order.getStartLng());
                        map.put("startPrice", order.getStartPrice());
                        map.put("status", order.getStatus());
                        map.put("guoluMoney", order.getGuoluMoney());
                        map.put("yuanchengMoney", order.getYuanchengMoney());
                        map.put("otherMoney", order.getOtherMoney());
                        String serviceTypeStr = "立即用车";
                        com.ybkj.daijia.server.zhuan.Order.ServiceType serviceType = order.getServiceType();
                        if (null != serviceType && serviceType.compareTo(Order.ServiceType.tangzu) == 0) {
                            if (new Date(order.getCreated().getTime() + 3600 * 1000).after(order.getServerTime())) {// 一小时内立即,一小时外预约用车
                                serviceTypeStr = "立即用车";
                            } else {
                                serviceTypeStr = "预约用车";
                            }
                        }
                        if (null != serviceType && serviceType.compareTo(Order.ServiceType.rizu) == 0) {
                            serviceTypeStr = "日租";
                        }
                        if (null != serviceType && serviceType.compareTo(Order.ServiceType.banrizu) == 0) {
                            serviceTypeStr = "半日租";
                        }
                        if (null != serviceType && serviceType.compareTo(Order.ServiceType.jieji) == 0) {
                            if (new Date(order.getCreated().getTime() + 3600 * 1000).after(order.getServerTime())) {
                                serviceTypeStr = "立即接机";
                            } else {
                                serviceTypeStr = "预约接机";
                            }
                        }
                        if (null != serviceType && serviceType.compareTo(Order.ServiceType.songji) == 0) {
                            if (new Date(order.getCreated().getTime() + 3600 * 1000).after(order.getServerTime())) {
                                serviceTypeStr = "立即送机";
                            } else {
                                serviceTypeStr = "预约送机";
                            }
                        }
                        if (null != serviceType && serviceType.compareTo(Order.ServiceType.jiezhan) == 0) {
                            if (new Date(order.getCreated().getTime() + 3600 * 1000).after(order.getServerTime())) {
                                serviceTypeStr = "立即接站";
                            } else {
                                serviceTypeStr = "预约接站";
                            }
                        }
                        if (null != serviceType && serviceType.compareTo(Order.ServiceType.songzhan) == 0) {
                            if (new Date(order.getCreated().getTime() + 3600 * 1000).after(order.getServerTime())) {
                                serviceTypeStr = "立即送站";
                            } else {
                                serviceTypeStr = "预约送站";
                            }
                        }
                        map.put("serviceType", serviceTypeStr);
                        String orderMemo = "";
                        if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {
                            List<OrderMemo> orderMemos = order.getOrderMemos();
                            for (int i = 0; i < orderMemos.size(); i++) {
                                orderMemo += ((i + 1) + ":");
                                orderMemo += (orderMemos.get(i).getMemo() + "\n");
                            }
                        }
                        map.put("orderMemo", orderMemo);
                        String memoStr = "";
                        if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {
                            List<OrderMemo> orderMemos = order.getOrderMemos();
                            for (int i = 0; i < orderMemos.size(); i++) {
                                memoStr += (orderMemos.get(i).getMemo());
                            }
                        }
                        map.put("memoStr", memoStr);
                        map.put("couponId", order.getCouponId());
                        content.add(map);
                    }
                }
                session.removeAttribute("exportZhuancheProcess");
            }
        }

        return content;
    }

    @Override
    public List<Order> queryByEmployId(Long employId, String status) {
        List<Order> list = new ArrayList<Order>();
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDER).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (employId != null && employId != 0) {
            kv.put("employId", String.valueOf(employId));
            builder.append("&employId={employId}");
        }
        if (status != null) {
            kv.put("status", status);
            builder.append("&status={status}");
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
                if (list != null && list.size() != 0) {
                    for (Order order : list) {
                        Area area = areaMapper.selectByPrimaryKeyWithCharge(order.getAreaId());
                        order.setArea(area);
                    }
                }
            }
        }
        return list;
    }

    @Override
    public Page<Order> queryZhuanOrder(Long companyId, String orderNo, Long employId, String employName, String employPhone, String passengerName,
        String passengerPhone, String carNumber, Integer status) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDER).append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        kv.put("orderby", "status asc,id desc");
        builder.append("&orderby={orderby}");
        if (companyId != null && companyId != 0) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        if (employId != null && employId != 0) {
            kv.put("employId", String.valueOf(employId));
            builder.append("&employId={employId}");
        }
        if (StringUtils.isNotBlank(orderNo)) {
            kv.put("orderNo", orderNo);
            builder.append("&orderNo={orderNo}");
        }
        if (StringUtils.isNotBlank(employName)) {
            kv.put("employName", employName);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(employPhone)) {
            kv.put("employPhone", employPhone);
            builder.append("&employPhone={employPhone}");
        }
        if (StringUtils.isNotBlank(passengerName)) {
            kv.put("passengerName", passengerName);
            builder.append("&passengerName={passengerName}");
        }
        if (StringUtils.isNotBlank(passengerPhone)) {
            kv.put("passengerPhone", passengerPhone);
            builder.append("&passengerPhone={passengerPhone}");
        }
        if (StringUtils.isNotBlank(carNumber)) {
            kv.put("carNumber", carNumber);
            builder.append("&carNumber={carNumber}");
        }
        if (status != null && status != -1) {
            if (status == 0) {
                kv.put("status", "new");
            } else if (status == 1) {
                kv.put("status", "pai");
            } else if (status == 2) {
                kv.put("status", "jie");
            } else if (status == 3) {
                kv.put("status", "run");
            } else if (status == 4) {
                kv.put("status", "finish");
            } else if (status == 5) {
                kv.put("status", "cancel");
            }
            builder.append("&status={status}");
        } else {
            kv.put("status", "uncancel");
            builder.append("&status={status}");
        }
        List<Order> list = new ArrayList<Order>();
        long total = 0;
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
            for (Order order : list) {
                if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {

                    StringBuilder memoStr = new StringBuilder();
                    List<OrderMemo> orderMemos = order.getOrderMemos();
                    for (int i = 0; i < orderMemos.size(); i++) {
                        memoStr.append((i + 1) + ":");
                        memoStr.append(orderMemos.get(i).getMemo() + "\n");
                    }
                    order.setOrderMemo(memoStr.toString());
                }
            }
        }
        return new PageImpl<Order>(list, pageable, total);
    }

    @Override
    public Result<Order> createOrder(Long passengerId, String passengerName, String passengerPhone, String showPhone, Long companyId,
        String companyName, Long carTypeId, String startAddress, String startAddressDetail, Double startLat, Double startLng, String endAddress,
        String endAddressDetail, Double endLat, Double endLng, Date serverTime, Double budgetPay, Double preStartPrice, Double preMileagePrice,
        Double preRunTimePrice, Integer preTravelTime, Double preMileage, Long employId, String channelName, Long couponId, String operator) {
        Result<Order> r = new Result<Order>();
        Passenger passenger = new Passenger();
        if (passengerId == null) {
            if (StringUtils.isNotBlank(passengerName)) {
                passenger.setName(passengerName);
            } else {
                passenger.setName("先生/女士");
            }
            passenger.setPhone(showPhone);
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_PHONE);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(startLng);
            passenger.setLatitude(startLat);
            passenger.setCompanyId(companyId);
            passenger.setCompanyName(companyName);
            try {
                Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());
                passenger = result.getResult();
                if (passenger.getId() == null || passenger.getId() == 0) {
                    r.setMessage("创建新乘客失败!");
                    r.setSuccess(false);
                    return r;
                }
            } catch (Exception e) {
                e.printStackTrace();
                r.setMessage("创建新乘客失败!");
                r.setSuccess(false);
                return r;
            }

        } else {
            Result<Passenger> result = passengerApi.findOnePassenger(passengerId, settingUtils.get());
            passenger = result.getResult();
        }
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("passengerId", String.valueOf(passenger.getId()));
        kv.add("passengerName", passenger.getName());
        kv.add("passengerPhone", passenger.getPhone());
        kv.add("showPhone", showPhone);
        kv.add("companyId", String.valueOf(companyId));
        kv.add("companyName", companyName);
        kv.add("carTypeId", String.valueOf(carTypeId));
        kv.add("channelName", channelName);
        kv.add("startAddress", startAddress);
        if (StringUtils.isNotBlank(startAddressDetail)) {
            kv.add("startAddressDetail", startAddressDetail);
        }
        if (StringUtils.isNotBlank(endAddressDetail)) {
            kv.add("endAddressDetail", endAddressDetail);
        }
        if (couponId != null) {
            kv.add("couponId", couponId + "");
        }
        kv.add("startLat", String.valueOf(startLat));
        kv.add("startLng", String.valueOf(startLng));
        if (StringUtils.isNotBlank(endAddress) && endLat != null && endLng != null) {
            kv.add("endAddress", endAddress);
            kv.add("endLat", String.valueOf(endLat));
            kv.add("endLng", String.valueOf(endLng));
        }
        kv.add("serverTime", String.valueOf(serverTime.getTime()));
        if (null != budgetPay) {
            kv.add("budgetPay", String.valueOf(budgetPay));
        }
        if (null != preStartPrice) {
            kv.add("preStartPrice", String.valueOf(preStartPrice));
        }
        if (null != preMileagePrice) {
            kv.add("preMileagePrice", String.valueOf(preMileagePrice));
        }
        if (null != preRunTimePrice) {
            kv.add("preRunTimePrice", String.valueOf(preRunTimePrice));
        }
        if (null != preTravelTime) {
            kv.add("preTravelTime", String.valueOf(preTravelTime));
        }
        if (null != preMileage) {
            kv.add("preMileage", String.valueOf(preMileage));
        }
        if (!"微信预约".equals(channelName) && !"网站预约".equals(channelName) && !"客户经理".equals(channelName)) {
            kv.add("prePay", String.valueOf(settingUtils.get().isZhuanchePrePay()));
        }
        if (employId != null && employId != 0) {
            Driver driver = driverMapper.selectByPrimaryKey(employId);
            if (driver != null) {
                kv.add("employId", String.valueOf(employId));
                kv.add("employCompanyId", String.valueOf(driver.getCompanyId()));
                kv.add("employName", driver.getName());
                kv.add("employPhone", driver.getPhone());
                kv.add("employNo", driver.getUsername());
                kv.add("employPhoto", driver.getPhoto());
                kv.add("employScore", String.valueOf(driver.getStarLevel()));
            }
        }
        if (StringUtils.isNotBlank(operator)) {
            kv.add("operator", operator);
        }
        String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.CREATE_ORDER, kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Long orderId = data.getLong("id");
                Order order = findOne(orderId);
                r.setResult(order);
                r.setSuccess(true);
                if (employId != null && order.getStatus() == 1) {
                    driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER, Driver.DRIVER_JOBSTATUS_ZHUANCHE, employId);
                }
            } else {
                String message = jo.getString("message");
                r.setMessage(message);
                r.setSuccess(false);
            }
        }
        return r;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Order> cancelOrder(Order order, String cancelCause, String operator, String who) {

        Result<Order> result = new Result<Order>();
        result.setSuccess(false);
        StringBuilder builder = new StringBuilder();
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("cause", cancelCause);
        if ("appCancel".equals(who)) {
            // 司机销单
            builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.CANCEL).append("?orderId={orderId}&cause={cause}&appKey={appKey}");
        } else if ("adminCancel".equals(who)) {
            // 后台管理系统销单
            builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.CANCEL_ORDER).append("?orderId={orderId}&operator={operator}&cause={cause}&appKey={appKey}");
            kv.put("operator", operator);
        } else if ("customerCancel".equals(who)) {
            // 公众号销单
            builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.PAIDAN_ORDER).append("?orderId={orderId}&operator={operator}&cause={cause}&action={action}&appKey={appKey}");
            kv.put("action", "cancel");
            kv.put("operator", operator);
        } else if ("system".equals(who)) {
            // 公众号销单
            builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.PAIDAN_ORDER).append("?orderId={orderId}&operator={operator}&cause={cause}&action={action}&appKey={appKey}");
            kv.put("action", "cancel");
            kv.put("operator", operator);
        }
        String resultStr = zhuanApi.put(builder.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            result.setMessage("销单失败");
        } else {
            result.setSuccess(true);

            Driver driver = null;
            if (null != order.getEmployId()) {
                driver = driverMapper.selectByPrimaryKey(order.getEmployId());
                if (null != driver) {
                    if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null, driver.getId());
                    }
                    cacheManager.removeDriverCache(driver.getId());
                }
            }

            ZhuanOrderCancelEvent cancelEvent = new ZhuanOrderCancelEvent(order, driver, who);
            applicationEventMulticaster.multicastEvent(cancelEvent);

            // 销单退款
            if (null != order.getPrePayTypeDetail() && !order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                Result<Passenger> result_p = passengerApi.findOnePassenger(order.getPassengerId(), settingUtils.get());
                Passenger passenger = result_p.getResult();
                if (null != passenger) {
                    BigDecimal coupon_hasPayed = BigDecimal.ZERO;
                    if (null != order.getCouponId()) {
                        Coupon coupon = salesApi.findOneCoupon(order.getCouponId()).getResult();
                        if (null != coupon) {
                            if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
                                coupon_hasPayed = coupon.getCouponRule().getMoney();
                            } else if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DISCOUNT)) {
                                Double discount = coupon.getCouponRule().getDiscount();
                                coupon_hasPayed = new BigDecimal(order.getBudgetPay()).multiply(
                                    new BigDecimal(1).subtract(new BigDecimal(discount).divide(new BigDecimal(10)))).setScale(0,
                                    BigDecimal.ROUND_DOWN);
                            }
                        }
                    }
                    BigDecimal tuikuan = new BigDecimal(order.getBudgetPay()).subtract(coupon_hasPayed);
                    if (tuikuan.doubleValue() > 0) {
                        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                            passengerApi.createPassengerAccount(passenger, null, tuikuan, PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                PassengerAccount.OPERATING_SYS, "销单退款:" + cancelCause, order.getId(), order.getOrderNo(),
                                PassengerAccount.ORDER_TYPE_ZHUANCHE, null, true, false, settingUtils.get());
                        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                            Enterprise enterprise = passengerApi.findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
                            if (null != enterprise) {
                                passengerApi.createEnterpriseAccount(enterprise, tuikuan, PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                    PassengerAccount.OPERATING_SYS, "销单退款:" + cancelCause, order.getId(), order.getOrderNo(),
                                    PassengerAccount.ORDER_TYPE_ZHUANCHE, null, true, false, settingUtils.get());
                            }
                        }
                    }
                }
            }

        }
        superviceService.pushDdcx(order, cancelCause, who);
        return result;
    }

    @Override
    public Order findOne(Long id) {
        Order order = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDER_ONE)
            .append("?orderId={orderId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(id));
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                order = gson.fromJson(data.toString(), Order.class);
            }
        }
        return order;
    }

    @Override
    public OrderOrbit findOrbitByOrderId(Long id) {

        OrderOrbit orderOrbit = new OrderOrbit();
        try {

            StringBuilder builder = new StringBuilder();
            builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDERORBIT)
                .append("?orderId={orderId}&appKey={appKey}");
            Map<String, String> kv = new HashMap<String, String>();
            kv.put("orderId", String.valueOf(id));
            String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    orderOrbit = gson.fromJson(data.toString(), OrderOrbit.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orderOrbit;
    }

    @Override
    public Order tempToForever(Long orderId, PayTypeDetails prePayType, Coupon coupon) {
        Order order = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.TEMP_TO_FOREVER)
            .append("?orderId={orderId}&prePayTypeDetail={prePayTypeDetail}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(orderId));
        kv.put("prePayTypeDetail", prePayType.toString());
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                order = gson.fromJson(data.toString(), Order.class);

                if (null != coupon && coupon.getStatus().equals(Coupon.COUPON_STATUS_NOTUSE)) {
                    coupon.setStatus(Coupon.COUPON_STATUS_HASUSED);
                    salesApi.updateCoupon(coupon);
                }
            }
        }
        return order;
    }

    @Override
    public Order tempToForeverV4up(Long orderId, PayTypeDetails prePayType, Coupon coupon) {
        Order order = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.TEMP_TO_FOREVER_V4UP)
            .append("?orderId={orderId}&prePayTypeDetail={prePayTypeDetail}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(orderId));
        kv.put("prePayTypeDetail", prePayType.toString());
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                order = gson.fromJson(data.toString(), Order.class);
                if (null != coupon && coupon.getStatus().equals(Coupon.COUPON_STATUS_NOTUSE)) {
                    coupon.setStatus(Coupon.COUPON_STATUS_HASUSED);
                    salesApi.updateCoupon(coupon);
                }
            }
        }
        return order;
    }

    // 添加订单备注
    @Override
    public void remark(Long id, String memo) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("orderId", String.valueOf(id));
        kv.add("memo", memo);
        kv.add("operator", operator);

        String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.CREATE_ORDERMEMO, kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code != 0) {
                throw new RuntimeException();
            }
        }
    }

    // 评价
    @Override
    public void review(Long id, String content, Double score) {

    }

    @Override
    public Result<Order> paidan(Driver driver, Order order, String operator) {

        Setting setting = settingUtils.get();

        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.PAIDAN_ORDER).append("?action={action}&operator={operator}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("operator", operator);
        kv.put("action", "paidan");

        sb.append("&orderId={orderId}");
        kv.put("orderId", String.valueOf(order.getId()));

        sb.append("&employId={employId}&employName={employName}&employPhone={employPhone}&employNo={employNo}&employPhoto={employPhoto}&employScore={employScore}&employCompanyId={employCompanyId}");
        kv.put("employId", String.valueOf(driver.getId()));
        kv.put("employName", driver.getName());
        kv.put("employPhone", driver.getPhone());
        kv.put("employNo", driver.getUsername());
        try {
            kv.put("employPhoto", URLEncoder.encode(settingUtils.get().getWebUrl() + "/upload/driver/" + driver.getPhoto(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        kv.put("employScore", String.valueOf(driver.getStarLevel()));
        kv.put("employCompanyId", String.valueOf(driver.getCompanyId()));
        String resultStr = zhuanApi.put(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            Integer isBook = order.getBookStatus();
            if (null == isBook || isBook.equals(0)) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER, Driver.DRIVER_JOBSTATUS_ZHUANCHE, driver.getId());
            }
            result.setSuccess(true);

            //自动收回
            if (setting.getRevokeTime() != 0) {
                try {
                    //专车订单自动收回定时器
                    Timer timer = new Timer();
                    OrderRevokeTimerTask orderRevokeTimerTask = new OrderRevokeTimerTask(order.getId(), "zhuanche", applicationEventMulticaster);
                    Integer howLong = setting.getRevokeTime();
                    timer.schedule(orderRevokeTimerTask, howLong * 1000);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }

        return result;
    }

    @Override
    public Result<Order> autoPaidan(Driver driver, Order order) {

        Setting setting = settingUtils.get();

        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.AUTO_PAIDAN_ORDER).append("?appKey={appKey}&orderId={orderId}");
        builder.append("&employId={employId}&employName={employName}&employPhone={employPhone}"
            + "&employNo={employNo}&employPhoto={employPhoto}&employScore={employScore}" + "&employCompanyId={employCompanyId}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("employId", String.valueOf(driver.getId()));
        kv.put("employName", driver.getName());
        kv.put("employPhone", driver.getPhone());
        kv.put("employNo", driver.getUsername());
        try {
            kv.put("employPhoto", URLEncoder.encode(settingUtils.get().getWebUrl() + "/upload/driver/" + driver.getPhoto(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        kv.put("employScore", String.valueOf(driver.getStarLevel()));
        kv.put("employCompanyId", String.valueOf(driver.getCompanyId()));

        String resultStr = zhuanApi.put(builder.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            if (null == order.getBookStatus() || order.getBookStatus() == 0) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER, Driver.DRIVER_JOBSTATUS_ZHUANCHE, driver.getId());
            }
            result.setSuccess(true);

            //自动收回
            if (setting.getRevokeTime() != 0) {
                try {
                    //专车订单自动收回定时器
                    Timer timer = new Timer();
                    OrderRevokeTimerTask orderRevokeTimerTask = new OrderRevokeTimerTask(order.getId(), "zhuanche", applicationEventMulticaster);
                    Integer howLong = setting.getRevokeTime();
                    timer.schedule(orderRevokeTimerTask, howLong * 1000);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }

        }
        return result;
    }

    @Override
    public Long countBusyAmount(Long id) {
        return null;
    }

    @Override
    public Result<Order> callback(Long id, String cause) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.CALLBACK).append("?appKey={appKey}");
        sb.append("&orderId={orderId}");
        sb.append("&action={action}");
        sb.append("&operator={operator}");
        sb.append("&cause={cause}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(id));
        kv.put("action", "callback");
        kv.put("cause", cause);
        kv.put("operator", operator);

        String resultStr = zhuanApi.put(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            result.setSuccess(true);
        }

        return result;
    }

    @Override
    public List<PassengerConcats> findPassengerConcats(Long passengerId) {
        return null;
    }

    @Override
    public PassengerAddress findPassengerToPlace(Long passengerId, Integer type) {
        return null;
    }

    @Override
    public Result<Order> completeTask(Order order) {
        return null;
    }

    @Override
    public List<Order> selectCuidan() {
        List<Order> list = new ArrayList<Order>();

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_CUIDAN).append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();

        String result = zhuanApi.get(sb.toString(), kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray ja = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public void closeCuidan(Long orderId) {
        StringBuilder sb = new StringBuilder();
        sb.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.CLOSE_CUIDAN).append("?appKey={appKey}");
        sb.append("&orderId={orderId}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(orderId));

        zhuanApi.put(sb.toString(), kv, settingUtils.get());
    }

    @Override
    public Page<CarType> queryByCompanyCarTypes(String companyName) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        List<CarType> list = new ArrayList<CarType>();
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_CARTYPE_COMPANY).append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", String.valueOf(companyName));
            builder.append("&companyName={companyName}");
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());

        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<CarType>>() {
                }.getType());
                total = list.size();
            }
        }
        // 统计条数
        try {
            StringBuilder builder2 = new StringBuilder();
            builder2.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.COUNT_CARTYPE_COMPANY).append("?appKey={appKey}");
            Map<String, String> kv2 = new HashMap<String, String>();
            if (StringUtils.isNotBlank(companyName)) {
                kv2.put("companyName", String.valueOf(companyName));
                builder2.append("&companyName={companyName}");
            }
            String result2 = zhuanApi.get(builder2.toString(), kv2, settingUtils.get());
            if (result2 != null) {
                JSONObject jo = new JSONObject(result2);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    Long count = jo.getLong("data");
                    if (count != null) {
                        total = count;
                    }
                }
            }

        } catch (Exception e) {
        }

        return new PageImpl<CarType>(list, pageable, total);
    }

    // 到专车系统查询车辆类型
    @Override
    public List<CarType> queryCarTypes(Long companyId) {
        List<CarType> list = new ArrayList<CarType>();

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_CARTYPE).append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        if (companyId != null && companyId != 0) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                list = gson.fromJson(data.toString(), new TypeToken<List<CarType>>() {
                }.getType());
                if (list != null && list.size() != 0) {
                    for (CarType carType : list) {
                        Area area = areaMapper.selectByPrimaryKey(carType.getAreaId());
                        if (area != null) {
                            carType.setAreaName(area.getName());
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<CarType> queryCarTypeV4up(Long companyId) {

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_CARTYPES_V4UP).append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        if (companyId != null && companyId != 0) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());

        List<CarType> list = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<CarType>>() {
                }.getType());
            }
        }
        return list;
    }

    // 到专车系统查询车辆类型
    @Override
    public CarType findCarType(Long carTypeId) {
        CarType carType = null;
        if (carTypeId == null) {
            return carType;
        }
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_CARTYPE_ONE).append("?carTypeId={carTypeId}&appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carTypeId", String.valueOf(carTypeId));

        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = null;
            code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                carType = gson.fromJson(data.toString(), CarType.class);
            }
        }
        return carType;
    }

    // 到专车系统删除车辆类型
    @Override
    public int deleteCarType(Long id) {
        int i = 0;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.DELETE_CARTYPE).append("?carTypeId={carTypeId}&appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carTypeId", String.valueOf(id));
        String result = zhuanApi.delete(builder.toString(), kv, settingUtils.get());
        if (StringUtils.isBlank(result)) {
            i = 1;
        }
        return i;
    }

    @Override
    public Map<String, Object> deleteCarTypeV4up(Long id) {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.DELETE_CARTYPE_V4UP);

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("carTypeId", String.valueOf(id));
        String result = zhuanApi.postMultiValueMap(builder.toString(), kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        String message = jo.getString("message");
        map.put("code", code);
        map.put("message", message);
        return map;
    }

    // 到专车系统新建车辆类型
    @Override
    public Map<String, Object> createCarType(String name, Integer sequence, String picture, String ifTaxi, String accessibleType) {
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("typeName", name);
        kv.add("sequence", String.valueOf(sequence));
        kv.add("ifTaxi", ifTaxi);
        kv.add("accessibleType", accessibleType);
        if (StringUtils.isNotBlank(picture)) {
            kv.add("picture", picture);
        }
        String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.CREATE_CARTYPE_V4UP, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            JSONObject data = jo.getJSONObject("data");
            Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
            CarType carType = new CarType();
            carType = gson.fromJson(data.toString(), CarType.class);
            map.put("success", true);
            map.put("message", "添加成功!");
            map.put("data", carType);
        } else {
            String message = jo.getString("message");
            map.put("success", false);
            map.put("message", message);
        }
        return map;
    }

    // @Override
    // public Map<String, Object> createCarTypeV4up(
    // Long companyId, String companyName, String name, Integer sequence, String
    // picture,
    // Long tangzuAreaId,Long rizuAreaId,Long banrizuAreaId,Long
    // jiejiAreaId,Long songjiAreaId,Long jiezhanAreaId,Long songzhanAreaId,
    // String tangzuAreaName, String rizuAreaName, String banrizuAreaName,
    // String jiejiAreaName, String songjiAreaName,
    // String jiezhanAreaName, String songzhanAreaName) {
    // Map<String, Object> map = new HashMap<String, Object>();
    // MultiValueMap<String, String> kv = new LinkedMultiValueMap<String,
    // String>();
    // kv.add("companyId", String.valueOf(companyId));
    // kv.add("companyName", companyName);
    // kv.add("typeName", name);
    // kv.add("sequence", String.valueOf(sequence));
    // if (StringUtils.isNotBlank(picture)) {
    // kv.add("picture", picture);
    // }
    // kv.add("tangzuAreaId", String.valueOf(tangzuAreaId));
    // kv.add("rizuAreaId", String.valueOf(rizuAreaId));
    // kv.add("banrizuAreaId", String.valueOf(banrizuAreaId));
    // kv.add("jiejiAreaId", String.valueOf(jiejiAreaId));
    // kv.add("songjiAreaId", String.valueOf(songjiAreaId));
    // kv.add("jiezhanAreaId", String.valueOf(jiezhanAreaId));
    // kv.add("songzhanAreaId", String.valueOf(songzhanAreaId));
    // kv.add("tangzuAreaName", tangzuAreaName);
    // kv.add("rizuAreaName", rizuAreaName);
    // kv.add("banrizuAreaName", banrizuAreaName);
    // kv.add("jiejiAreaName", jiejiAreaName);
    // kv.add("songjiAreaName", songjiAreaName);
    // kv.add("jiezhanAreaName", jiezhanAreaName);
    // kv.add("songzhanAreaName", songzhanAreaName);
    //
    // String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() +
    // ZhuanApi.CREATE_CARTYPE_V4UP, kv, settingUtils.get());
    // JSONObject jo = new JSONObject(result);
    // Integer code = jo.getInt("code");
    // if (code == 0) {
    // JSONObject data = jo.getJSONObject("data");
    // Gson gson = new Gson();
    // CarType carType = new CarType();
    // carType = gson.fromJson(data.toString(), CarType.class);
    // map.put("success", true);
    // map.put("message", "添加成功!");
    // map.put("data", carType);
    // } else {
    // String message = jo.getString("message");
    // map.put("success", false);
    // map.put("message", message);
    // }
    // return map;
    // }
    @Override
    public Map<String, Object> startCarTypeCompany(Long carTypeId, Long companyId, String companyName, Long tangzuAreaId, Long rizuAreaId,
        Long banrizuAreaId, Long jiejiAreaId, Long songjiAreaId, Long jiezhanAreaId, Long songzhanAreaId, String tangzuAreaName,
        String rizuAreaName, String banrizuAreaName, String jiejiAreaName, String songjiAreaName, String jiezhanAreaName, String songzhanAreaName) {

        Map<String, Object> map = new HashMap<String, Object>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("carTypeId", String.valueOf(carTypeId));
        kv.add("companyId", String.valueOf(companyId));
        kv.add("companyName", companyName);
        kv.add("tangzuAreaId", String.valueOf(tangzuAreaId));
        kv.add("rizuAreaId", String.valueOf(rizuAreaId));
        kv.add("banrizuAreaId", String.valueOf(banrizuAreaId));
        kv.add("jiejiAreaId", String.valueOf(jiejiAreaId));
        kv.add("songjiAreaId", String.valueOf(songjiAreaId));
        kv.add("jiezhanAreaId", String.valueOf(jiezhanAreaId));
        kv.add("songzhanAreaId", String.valueOf(songzhanAreaId));
        kv.add("tangzuAreaName", tangzuAreaName);
        kv.add("rizuAreaName", rizuAreaName);
        kv.add("banrizuAreaName", banrizuAreaName);
        kv.add("jiejiAreaName", jiejiAreaName);
        kv.add("songjiAreaName", songjiAreaName);
        kv.add("jiezhanAreaName", jiezhanAreaName);
        kv.add("songzhanAreaName", songzhanAreaName);
        String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.SAVE_CARTYPE_COMPANY, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("success", true);
            map.put("message", "添加成功!");
        } else {
            String message = jo.getString("message");
            map.put("success", false);
            map.put("message", message);
        }
        return map;
    }

    @Override
    public Map<String, Object> updateCarTypeCompany(Long carTypeId, Long companyId, String companyName, Long tangzuAreaId, Long rizuAreaId,
        Long banrizuAreaId, Long jiejiAreaId, Long songjiAreaId, Long jiezhanAreaId, Long songzhanAreaId, String tangzuAreaName,
        String rizuAreaName, String banrizuAreaName, String jiejiAreaName, String songjiAreaName, String jiezhanAreaName, String songzhanAreaName) {

        Map<String, Object> map = new HashMap<String, Object>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("carTypeId", String.valueOf(carTypeId));
        kv.add("companyId", String.valueOf(companyId));
        kv.add("companyName", companyName);
        kv.add("tangzuAreaId", String.valueOf(tangzuAreaId));
        kv.add("rizuAreaId", String.valueOf(rizuAreaId));
        kv.add("banrizuAreaId", String.valueOf(banrizuAreaId));
        kv.add("jiejiAreaId", String.valueOf(jiejiAreaId));
        kv.add("songjiAreaId", String.valueOf(songjiAreaId));
        kv.add("jiezhanAreaId", String.valueOf(jiezhanAreaId));
        kv.add("songzhanAreaId", String.valueOf(songzhanAreaId));
        kv.add("tangzuAreaName", tangzuAreaName);
        kv.add("rizuAreaName", rizuAreaName);
        kv.add("banrizuAreaName", banrizuAreaName);
        kv.add("jiejiAreaName", jiejiAreaName);
        kv.add("songjiAreaName", songjiAreaName);
        kv.add("jiezhanAreaName", jiezhanAreaName);
        kv.add("songzhanAreaName", songzhanAreaName);
        String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.UPDATE_CARTYPE_COMPANY, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("success", true);
            map.put("message", "修改成功!");
        } else {
            String message = jo.getString("message");
            map.put("success", false);
            map.put("message", message);
        }
        return map;
    }

    // 到专车系统更新车辆类型
    @Override
    public int updateCarType(Long id, String name, Integer sequence, Long areaId, String picture) {
        int i = 0;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.UPDATE_CARTYPE)
            .append("?carTypeId={carTypeId}&typeName={typeName}&sequence={sequence}&areaId={areaId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carTypeId", String.valueOf(id));
        kv.put("typeName", name);
        kv.put("sequence", String.valueOf(sequence));
        kv.put("areaId", String.valueOf(areaId));
        if (StringUtils.isNotBlank(picture)) {
            kv.put("picture", picture);
            builder.append("&picture={picture}");
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            i = 1;
        }

        return i;
    }

    @Override
    public Map<String, Object> updateCarTypeV4up(Long id, String name, Integer sequence, String picture, String ifTaxi, String accessibleType) {
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("carTypeId", String.valueOf(id));
        kv.add("typeName", name);
        kv.add("sequence", String.valueOf(sequence));
        if (StringUtils.isNotBlank(ifTaxi)) {
            kv.add("ifTaxi", ifTaxi);
        }
        if (StringUtils.isNotBlank(accessibleType)) {
            kv.add("accessibleType", accessibleType);
        }
        if (StringUtils.isNotBlank(picture)) {
            kv.add("picture", picture);
        }

        String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.UPDATE_CARTYPE_V4UP, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("success", true);
            map.put("message", "修改成功!");
        } else {
            String message = jo.getString("message");
            map.put("success", false);
            map.put("message", message);
        }
        return map;
    }

    @Override
    public Page<Car> queryCars(Long companyId, Long carTypeId, String carNumber, String employName, Integer status) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_CAR).append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (companyId != null && companyId != 0) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        if (carTypeId != null && carTypeId != 0) {
            kv.put("carTypeId", String.valueOf(carTypeId));
            builder.append("&carTypeId={carTypeId}");
        }
        if (StringUtils.isNotBlank(carNumber)) {
            kv.put("carNumber", carNumber);
            builder.append("&carNumber={carNumber}");
        }
        if (StringUtils.isNotBlank(employName)) {
            kv.put("employName", employName);
            builder.append("&employName={employName}");
        }
        if (status != null && status != -1) {
            kv.put("status", String.valueOf(status));
            builder.append("&status={status}");
        }
        List<Car> list = new ArrayList<Car>();
        long total = 0;
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        return new PageImpl<Car>(list, pageable, total);
    }

    @Override
    public Page<Car> queryByParamsCars(String companyName, String carType, String carNumber, String employName, String status) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_PARAMS_CARS).append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", String.valueOf(companyName));
            builder.append("&companyName={companyName}");
        }
        if (StringUtils.isNotBlank(carType)) {
            kv.put("carType", String.valueOf(carType));
            builder.append("&carType={carType}");
        }
        if (StringUtils.isNotBlank(carNumber)) {
            kv.put("carNumber", carNumber);
            builder.append("&carNumber={carNumber}");
        }
        if (StringUtils.isNotBlank(employName)) {
            kv.put("employName", employName);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(status)) {
            kv.put("status", String.valueOf(status));
            builder.append("&status={status}");
        }
        List<Car> list = new ArrayList<Car>();
        long total = 0;
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        return new PageImpl<Car>(list, pageable, total);
    }

    @Override
    public Page<Car> queryByParamsCarsV4up(Long companyId, String companyName, String carType, String carNumber, String employName, String status,
        String isPlatforms) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_PARAMS_CARS_V4UP).append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", String.valueOf(companyName));
            builder.append("&companyName={companyName}");
        }
        if (StringUtils.isNotBlank(carType)) {
            kv.put("carType", String.valueOf(carType));
            builder.append("&carType={carType}");
        }
        if (StringUtils.isNotBlank(carNumber)) {
            kv.put("carNumber", carNumber);
            builder.append("&carNumber={carNumber}");
        }
        if (StringUtils.isNotBlank(employName)) {
            kv.put("employName", employName);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(status)) {
            kv.put("status", String.valueOf(status));
            builder.append("&status={status}");
        }
        if (StringUtils.isNotBlank(isPlatforms)) {
            kv.put("isPlatforms", String.valueOf(isPlatforms));
            builder.append("&isPlatforms={isPlatforms}");
        }
        List<Car> list = new ArrayList<Car>();
        long total = 0;
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        return new PageImpl<Car>(list, pageable, total);
    }

    @Override
    public int deleteCar(Long id) {
        int i = 0;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.DELETE_CAR).append("?carId={carId}&appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carId", String.valueOf(id));
        String result = zhuanApi.delete(builder.toString(), kv, settingUtils.get());
        if (StringUtils.isBlank(result)) {
            i = 1;
        }
        return i;
    }

    @Override
    public Map<String, Object> createCar(Car obj) throws ParseException {
        Map<String, Object> map = new HashMap<String, Object>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("companyId", String.valueOf(obj.getCompanyId()));
        kv.add("companyName", obj.getCompanyName());
        kv.add("carName", obj.getCarName());
        kv.add("carNumber", obj.getCarNumber());
        kv.add("carTypeId", String.valueOf(obj.getCarTypeId()));
        kv.add("drivingDistance", String.valueOf(obj.getDrivingDistance()));
        kv.add("buyTime", String.valueOf(obj.getBuyTime().getTime()));
        kv.add("limitLine", String.valueOf(obj.getLimitLine()));
        kv.add("insuranceTime", String.valueOf(obj.getInsuranceTime().getTime()));
        kv.add("overhaulTime", String.valueOf(obj.getOverhaulTime().getTime()));
        if (obj.getEmployId() != null && obj.getEmployId() != 0) {
            kv.add("employId", String.valueOf(obj.getEmployId()));
        }
        if (StringUtils.isNotBlank(obj.getEmployName())) {
            kv.add("employName", obj.getEmployName());
        }

        if (StringUtils.isNotBlank(obj.getPlateColor())) {
            kv.add("plateColor", obj.getPlateColor());
        }
        if (StringUtils.isNotBlank(obj.getBrand())) {
            kv.add("brand", obj.getBrand());
        }
        if (StringUtils.isNotBlank(obj.getVehicleType())) {
            kv.add("vehicleType", obj.getVehicleType());
        }
        if (StringUtils.isNotBlank(obj.getVehicleModel())) {
            kv.add("vehicleModel", obj.getVehicleModel());
        }
        if (StringUtils.isNotBlank(obj.getOwner())) {
            kv.add("owner", obj.getOwner());
        }
        if (StringUtils.isNotBlank(obj.getDriverProType())) {
            kv.add("driverProType", obj.getDriverProType());
        }
        if (StringUtils.isNotBlank(obj.getBodyColor())) {
            kv.add("bodyColor", obj.getBodyColor());
        }
        if (StringUtils.isNotBlank(obj.getEngineNo())) {
            kv.add("engineNo", obj.getEngineNo());
        }
        if (StringUtils.isNotBlank(obj.getVin())) {
            kv.add("vin", obj.getVin());
        }
        if (StringUtils.isNotBlank(obj.getFuel())) {
            kv.add("fuel", obj.getFuel());
        }
        if (StringUtils.isNotBlank(obj.getPermitted())) {
            kv.add("permitted", obj.getPermitted());
        }
        if (null != obj.getRegistrationTime()) {
            kv.add("registrationTime", String.valueOf(obj.getRegistrationTime().getTime()));
        }
        if (null != obj.getInspectioStatus()) {
            kv.add("inspectioStatus", String.valueOf(obj.getInspectioStatus()));
        }
        if (null != obj.getRateType()) {
            kv.add("rateType", String.valueOf(obj.getRateType()));
        }
        if (null != obj.getVehicleStatus()) {
            kv.add("vehicleStatus", String.valueOf(obj.getVehicleStatus()));
        }
        if (StringUtils.isNotBlank(obj.getDisplacement())) {
            kv.add("displacement", obj.getDisplacement());
        }
        if (null != obj.getMaintenanceStatus()) {
            kv.add("maintenanceStatus", String.valueOf(obj.getMaintenanceStatus()));
        }
        if (null != obj.getNextOverhaulTime()) {
            kv.add("nextOverhaulTime", String.valueOf(obj.getNextOverhaulTime().getTime()));
        }
        if (StringUtils.isNotBlank(obj.getTaxiNo())) {
            kv.add("taxiNo", obj.getTaxiNo());
        }
        if (StringUtils.isNotBlank(obj.getTaxiAgency())) {
            kv.add("taxiAgency", obj.getTaxiAgency());
        }
        if (StringUtils.isNotBlank(obj.getTaxiRegion())) {
            kv.add("taxiRegion", obj.getTaxiRegion());
        }
        if (null != obj.getValidTime()) {
            kv.add("validTime", String.valueOf(obj.getValidTime().getTime()));
        }
        if (null != obj.getInvalidTime()) {
            kv.add("invalidTime", String.valueOf(obj.getInvalidTime().getTime()));
        }
        if (null != obj.getTaxiRegisterTime()) {
            kv.add("taxiRegisterTime", String.valueOf(obj.getTaxiRegisterTime().getTime()));
        }
        if (null != obj.getDeviceInstallTime()) {
            kv.add("deviceInstallTime", String.valueOf(obj.getDeviceInstallTime().getTime()));
        }
        if (StringUtils.isNotBlank(obj.getDeviceSerial())) {
            kv.add("deviceSerial", obj.getDeviceSerial());
        }
        if (StringUtils.isNotBlank(obj.getDeviceBrand())) {
            kv.add("deviceBrand", obj.getDeviceBrand());
        }
        if (StringUtils.isNotBlank(obj.getDeviceModel())) {
            kv.add("deviceModel", obj.getDeviceModel());
        }
        if (StringUtils.isNotBlank(obj.getGpsIMEI())) {
            kv.add("gpsIMEI", obj.getGpsIMEI());
        }
        if (StringUtils.isNotBlank(obj.getProvincial())) {
            kv.add("provincial", obj.getProvincial() + "-" + obj.getCity() + "-" + obj.getCounty());
        }
        if (StringUtils.isNotBlank(obj.getAddress())) {
            kv.add("address", obj.getAddress());
        }
        if (StringUtils.isNotBlank(obj.getInsurer())) {
            kv.add("insurer", obj.getInsurer());
        }
        if (StringUtils.isNotBlank(obj.getInsuranceNo())) {
            kv.add("insuranceNo", obj.getInsuranceNo());
        }
        if (StringUtils.isNotBlank(obj.getInsType())) {
            kv.add("insType", obj.getInsType());
        }
        if (null != obj.getInsMoney()) {
            kv.add("insMoney", String.valueOf(obj.getInsMoney()));
        }
        if (null != obj.getInsValidTime()) {
            kv.add("insValidTime", String.valueOf(obj.getInsValidTime().getTime()));
        }
        if (StringUtils.isNotBlank(obj.getPicture())) {
            kv.add("picture", obj.getPicture());
        }
        if (StringUtils.isNotBlank(obj.getPlatePictureAddress())) {
            kv.add("platePictureAddress", obj.getPlatePictureAddress());
        }
        try {
            String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.CREATE_CAR, kv, settingUtils.get());
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                Car car = gson.fromJson(data.toString(), Car.class);
                if (car != null && obj.getEmployId() != null) {
                    Driver driver = driverMapper.selectByPrimaryKey(obj.getEmployId());
                    if (driver != null) {
                        driverMapper.updateCarId(obj.getEmployId(), car.getId());
                    }
                }
                map.put("success", true);
                map.put("message", "添加成功!");
            } else {
                String message = "添加失败!";
                map.put("success", false);
                map.put("message", message);
            }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "添加失败!");
        }

        return map;
    }

    @Override
    public List<Car> queryByInsuranceTime() {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_INSURANCETIME).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (!principal.isCompanyType()) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
        }
        List<Car> list = new ArrayList<Car>();
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray ja = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public Long queryByInsuranceTimeLong() {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_INSURANCETIME).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (!principal.isCompanyType()) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
        }
        List<Car> list = new ArrayList<Car>();
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray ja = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        long size = (long) list.size();
        return size;
    }

    @Override
    public List<Car> queryByOverhaulTime() {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_OVERHAULTIME).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (!principal.isCompanyType()) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
        }
        List<Car> list = new ArrayList<Car>();
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray ja = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public Long queryByOverhaulTimeLong() {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_OVERHAULTIME).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (!principal.isCompanyType()) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
        }
        List<Car> list = new ArrayList<Car>();
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray ja = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        long size = list.size();
        return size;
    }

    @Override
    public Car findCar(Long id) {

        return zhuanApi.findCar(id, settingUtils.get());

    }

    @Override
    public List<Order> findByDriverId(Long driverId, Integer status) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDERS).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (driverId != null) {
            kv.put("driverId", String.valueOf(driverId));
            builder.append("&driverId={driverId}");
        }
        if (status != null) {
            kv.put("status", String.valueOf(status));
            builder.append("&status={status}");
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        List<Order> list = new ArrayList<Order>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public Map<String, Object> updateCar(Car car) {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.UPDATE_CAR).append("?carId={carId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carId", String.valueOf(car.getId()));
        if (car.getCompanyId() != null && car.getCompanyId() != 0) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(car.getCompanyId()));
        }
        if (StringUtils.isNotBlank(car.getCompanyName())) {
            builder.append("&companyName={companyName}");
            kv.put("companyName", car.getCompanyName());
        }
        if (StringUtils.isNotBlank(car.getCarName())) {
            builder.append("&carName={carName}");
            kv.put("carName", car.getCarName());
        }
        if (StringUtils.isNotBlank(car.getCarNumber())) {
            builder.append("&carNumber={carNumber}");
            kv.put("carNumber", car.getCarNumber());
        }
        if (car.getCarTypeId() != null && car.getCarTypeId() != 0) {
            builder.append("&carTypeId={carTypeId}");
            kv.put("carTypeId", String.valueOf(car.getCarTypeId()));
        }
        if (car.getStatus() != null) {
            builder.append("&status={status}");
            kv.put("status", String.valueOf(car.getStatus()));
        }
        if (car.getDrivingDistance() != null && car.getDrivingDistance() != 0) {
            builder.append("&drivingDistance={drivingDistance}");
            kv.put("drivingDistance", String.valueOf(car.getDrivingDistance()));
        }
        if (car.getBuyTime() != null) {
            builder.append("&buyTime={buyTime}");
            kv.put("buyTime", String.valueOf(car.getBuyTime().getTime()));
        }
        if (car.getLimitLine() != null) {
            builder.append("&limitLine={limitLine}");
            kv.put("limitLine", String.valueOf(car.getLimitLine()));
        }
        if (car.getInsuranceTime() != null) {
            builder.append("&insuranceTime={insuranceTime}");
            kv.put("insuranceTime", String.valueOf(car.getInsuranceTime().getTime()));
        }
        if (car.getOverhaulTime() != null) {
            builder.append("&overhaulTime={overhaulTime}");
            kv.put("overhaulTime", String.valueOf(car.getOverhaulTime().getTime()));
        }

        if (car.getEmployId() != null && car.getEmployId() != 0) {
            kv.put("employId", String.valueOf(car.getEmployId()));
            builder.append("&employId={employId}");
        }
        if (StringUtils.isNotBlank(car.getEmployName())) {
            kv.put("employName", car.getEmployName());
            builder.append("&employName={employName}");
        } else {
            kv.put("employName", "-");
            builder.append("&employName={employName}");
        }

        if (StringUtils.isNotBlank(car.getPlateColor())) {
            kv.put("plateColor", car.getPlateColor());
            builder.append("&plateColor={plateColor}");
        }
        if (StringUtils.isNotBlank(car.getBrand())) {
            kv.put("brand", car.getBrand());
            builder.append("&brand={brand}");
        }
        if (StringUtils.isNotBlank(car.getVehicleType())) {
            kv.put("vehicleType", car.getVehicleType());
            builder.append("&vehicleType={vehicleType}");
        }
        if (StringUtils.isNotBlank(car.getVehicleModel())) {
            kv.put("vehicleModel", car.getVehicleModel());
            builder.append("&vehicleModel={vehicleModel}");
        }
        if (StringUtils.isNotBlank(car.getOwner())) {
            kv.put("owner", car.getOwner());
            builder.append("&owner={owner}");
        }
        if (StringUtils.isNotBlank(car.getDriverProType())) {
            kv.put("driverProType", car.getDriverProType());
            builder.append("&driverProType={driverProType}");
        }
        if (StringUtils.isNotBlank(car.getBodyColor())) {
            kv.put("bodyColor", car.getBodyColor());
            builder.append("&bodyColor={bodyColor}");
        }
        if (StringUtils.isNotBlank(car.getEngineNo())) {
            kv.put("engineNo", car.getEngineNo());
            builder.append("&engineNo={engineNo}");
        }
        if (StringUtils.isNotBlank(car.getVin())) {
            kv.put("vin", car.getVin());
            builder.append("&vin={vin}");
        }
        if (StringUtils.isNotBlank(car.getFuel())) {
            kv.put("fuel", car.getFuel());
            builder.append("&fuel={fuel}");
        }
        if (StringUtils.isNotBlank(car.getPermitted())) {
            kv.put("permitted", car.getPermitted());
            builder.append("&permitted={permitted}");
        }
        if (null != car.getRegistrationTime()) {
            kv.put("registrationTime", String.valueOf(car.getRegistrationTime().getTime()));
            builder.append("&registrationTime={registrationTime}");
        }
        if (null != car.getInspectioStatus()) {
            kv.put("inspectioStatus", String.valueOf(car.getInspectioStatus()));
            builder.append("&inspectioStatus={inspectioStatus}");
        }
        if (null != car.getRateType()) {
            kv.put("rateType", String.valueOf(car.getRateType()));
            builder.append("&rateType={rateType}");
        }
        if (null != car.getVehicleStatus()) {
            kv.put("vehicleStatus", String.valueOf(car.getVehicleStatus()));
            builder.append("&vehicleStatus={vehicleStatus}");
        }
        if (StringUtils.isNotBlank(car.getDisplacement())) {
            kv.put("displacement", car.getDisplacement());
            builder.append("&displacement={displacement}");
        }
        if (null != car.getMaintenanceStatus()) {
            kv.put("maintenanceStatus", String.valueOf(car.getMaintenanceStatus()));
            builder.append("&maintenanceStatus={maintenanceStatus}");
        }
        if (null != car.getNextOverhaulTime()) {
            kv.put("nextOverhaulTime", String.valueOf(car.getNextOverhaulTime().getTime()));
            builder.append("&nextOverhaulTime={nextOverhaulTime}");
        }
        if (StringUtils.isNotBlank(car.getTaxiNo())) {
            kv.put("taxiNo", car.getTaxiNo());
            builder.append("&taxiNo={taxiNo}");
        }
        if (StringUtils.isNotBlank(car.getTaxiAgency())) {
            kv.put("taxiAgency", car.getTaxiAgency());
            builder.append("&taxiAgency={taxiAgency}");
        }
        if (StringUtils.isNotBlank(car.getTaxiRegion())) {
            kv.put("taxiRegion", car.getTaxiRegion());
            builder.append("&taxiRegion={taxiRegion}");
        }
        if (null != car.getValidTime()) {
            kv.put("validTime", String.valueOf(car.getValidTime().getTime()));
            builder.append("&validTime={validTime}");
        }
        if (null != car.getInvalidTime()) {
            kv.put("invalidTime", String.valueOf(car.getInvalidTime().getTime()));
            builder.append("&invalidTime={invalidTime}");
        }
        if (null != car.getTaxiRegisterTime()) {
            kv.put("taxiRegisterTime", String.valueOf(car.getTaxiRegisterTime().getTime()));
            builder.append("&taxiRegisterTime={taxiRegisterTime}");
        }
        if (null != car.getDeviceInstallTime()) {
            kv.put("deviceInstallTime", String.valueOf(car.getDeviceInstallTime().getTime()));
            builder.append("&deviceInstallTime={deviceInstallTime}");
        }
        if (StringUtils.isNotBlank(car.getDeviceSerial())) {
            kv.put("deviceSerial", car.getDeviceSerial());
            builder.append("&deviceSerial={deviceSerial}");
        }
        if (StringUtils.isNotBlank(car.getDeviceBrand())) {
            kv.put("deviceBrand", car.getDeviceBrand());
            builder.append("&deviceBrand={deviceBrand}");
        }
        if (StringUtils.isNotBlank(car.getDeviceModel())) {
            kv.put("deviceModel", car.getDeviceModel());
            builder.append("&deviceModel={deviceModel}");
        }
        if (StringUtils.isNotBlank(car.getGpsIMEI())) {
            kv.put("gpsIMEI", car.getGpsIMEI());
            builder.append("&gpsIMEI={gpsIMEI}");
        }
        if (StringUtils.isNotBlank(car.getProvincial())) {
            kv.put("provincial", car.getProvincial());
            builder.append("&provincial={provincial}");
        }
        if (StringUtils.isNotBlank(car.getAddress())) {
            kv.put("address", car.getAddress());
            builder.append("&address={address}");
        }
        if (StringUtils.isNotBlank(car.getInsurer())) {
            kv.put("insurer", car.getInsurer());
            builder.append("&insurer={insurer}");
        }
        if (StringUtils.isNotBlank(car.getInsuranceNo())) {
            kv.put("insuranceNo", car.getInsuranceNo());
            builder.append("&insuranceNo={insuranceNo}");
        }
        if (StringUtils.isNotBlank(car.getInsType())) {
            kv.put("insType", car.getInsType());
            builder.append("&insType={insType}");
        }
        if (null != car.getInsMoney()) {
            kv.put("insMoney", String.valueOf(car.getInsMoney()));
            builder.append("&insMoney={insMoney}");
        }
        if (null != car.getInsValidTime()) {
            kv.put("insValidTime", String.valueOf(car.getInsValidTime().getTime()));
            builder.append("&insValidTime={insValidTime}");
        }
        if (StringUtils.isNotBlank(car.getPicture())) {
            kv.put("picture", car.getPicture());
            builder.append("&picture={picture}");
        }
        if (StringUtils.isNotBlank(car.getPlatePictureAddress())) {
            kv.put("platePictureAddress", car.getPlatePictureAddress());
            builder.append("&platePictureAddress={platePictureAddress}");
        }
        if (StringUtils.isNotBlank(car.getFlights())) {
            kv.put("flights", car.getFlights());
            builder.append("&flights={flights}");
        }
        String result = null;
        try {
            if (car.getEmployId() != null && StringUtils.isNotBlank(car.getEmployName()) && !"-".equals(car.getEmployName())) {
                Driver driver = driverMapper.selectByPrimaryKey(car.getEmployId()); // 新指派的员工
                if (null != driver) {
                    if (driver.getCarId() == null) { // 新员工的车辆id为空(正常指派)
                        Driver driver2 = driverMapper.selectByCarId(car.getId());
                        if (driver2 != null) {
                            driverMapper.updateCarId(driver2.getId(), null);
                        }
                        driverMapper.updateCarId(driver.getId(), car.getId());
                    } else if (driver.getCarId() != null) { // 新指派的员工有旧车辆
                        Driver driver2 = driverMapper.selectByCarId(car.getId());// 旧服务人员
                        if (driver2 != null && !driver.getId().equals(driver2.getId())) {
                            driverMapper.updateCarId(driver2.getId(), null);
                        }
                        driverMapper.updateCarId(driver.getId(), car.getId());
                    }
                }
            } else if (StringUtils.isBlank(car.getEmployName()) && car.getEmployId() != null) {
                Driver driver = driverMapper.selectByPrimaryKey(car.getEmployId());// 原来指派的员工
                driverMapper.updateCarId(driver.getId(), null);
            }

            result = zhuanApi.put(builder.toString(), kv, settingUtils.get());
        } catch (HttpClientErrorException e) {
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            result = e.getResponseBodyAsString();
        }

        if (StringUtils.isBlank(result)) {
            map.put("success", true);
            map.put("message", "修改成功！");
        } else {
            map.put("success", false);
            map.put("message", result);
        }
        return map;
    }

    @Override
    public Map<String, Object> updateCar(Long carId, Long companyId, String companyName, String carName, String carNumber, Long carTypeId,
        Integer status, Double drivingDistance, String buyTime, Long employId, String employName, Integer limitLine, String insuranceTime,
        String overhaulTime) {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.UPDATE_CAR).append("?carId={carId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carId", String.valueOf(carId));
        if (companyId != null && companyId != 0) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        if (StringUtils.isNotBlank(companyName)) {
            builder.append("&companyName={companyName}");
            kv.put("companyName", companyName);
        }
        if (StringUtils.isNotBlank(carName)) {
            builder.append("&carName={carName}");
            kv.put("carName", carName);
        }
        if (StringUtils.isNotBlank(carNumber)) {
            builder.append("&carNumber={carNumber}");
            kv.put("carNumber", carNumber);
        }
        if (carTypeId != null && carTypeId != 0) {
            builder.append("&carTypeId={carTypeId}");
            kv.put("carTypeId", String.valueOf(carTypeId));
        }
        if (status != null) {
            builder.append("&status={status}");
            kv.put("status", String.valueOf(status));
        }
        if (drivingDistance != null && drivingDistance != 0) {
            builder.append("&drivingDistance={drivingDistance}");
            kv.put("drivingDistance", String.valueOf(drivingDistance));
        }
        if (buyTime != null) {
            try {
                builder.append("&buyTime={buyTime}");
                kv.put("buyTime", String.valueOf(DateUtils.parseDate(buyTime, "yyyy-MM-dd").getTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (limitLine != null) {
            builder.append("&limitLine={limitLine}");
            kv.put("limitLine", String.valueOf(limitLine));
        }
        if (insuranceTime != null) {
            try {
                builder.append("&insuranceTime={insuranceTime}");
                kv.put("insuranceTime", String.valueOf(DateUtils.parseDate(insuranceTime, "yyyy-MM-dd").getTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (overhaulTime != null) {
            try {
                builder.append("&overhaulTime={overhaulTime}");
                kv.put("overhaulTime", String.valueOf(DateUtils.parseDate(overhaulTime, "yyyy-MM-dd").getTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (employId != null && employId != 0) {
            kv.put("employId", String.valueOf(employId));
            builder.append("&employId={employId}");
        }
        if (StringUtils.isNotBlank(employName)) {
            kv.put("employName", employName);
            builder.append("&employName={employName}");
        } else {
            kv.put("employName", "-");
            builder.append("&employName={employName}");
        }

        String result = null;
        try {
            if (employId != null && StringUtils.isNotBlank(employName)) {
                Driver driver = driverMapper.selectByPrimaryKey(employId); // 新指派的员工
                if (driver.getCarId() == null) { // 新员工的车辆id为空(正常指派)
                    Driver driver2 = driverMapper.selectByCarId(carId);
                    if (driver2 != null) {
                        driverMapper.updateCarId(driver2.getId(), null);
                    }
                    driverMapper.updateCarId(driver.getId(), carId);
                } else if (driver.getCarId() != null) { // 新指派的员工有旧车辆
                    Driver driver2 = driverMapper.selectByCarId(carId);// 旧服务人员
                    if (driver2 != null && !driver.getId().equals(driver2.getId())) {
                        driverMapper.updateCarId(driver2.getId(), null);
                    }
                    driverMapper.updateCarId(driver.getId(), carId);
                }
            } else if (StringUtils.isBlank(employName) && employId != null) {
                Driver driver = driverMapper.selectByPrimaryKey(employId);// 原来指派的员工
                driverMapper.updateCarId(driver.getId(), null);
            }

            result = zhuanApi.put(builder.toString(), kv, settingUtils.get());
        } catch (HttpClientErrorException e) {
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            result = e.getResponseBodyAsString();
        }

        if (StringUtils.isBlank(result)) {
            map.put("success", true);
            map.put("message", "修改成功！");
        } else {
            map.put("success", false);
            map.put("message", result);
        }
        return map;
    }

    @Override
    public List<Car> findByCarTypeId(Long carTypeId) {
        List<Car> list = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_CAR_TYPEID).append("?carTypeId={carTypeId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carTypeId", String.valueOf(carTypeId));
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }

        return list;
    }

    @Override
    public List<Order> listNewOrders() {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDER).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("status", "new");
        builder.append("&status={status}");

        kv.put("page", "1");
        builder.append("&page={page}");

        kv.put("rows", "20");
        builder.append("&rows={rows}");

        if (!principal.isCompanyType()) {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            builder.append("&companyId={companyId}");
        }

        List<Order> list = new ArrayList<Order>();
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
            for (Order order : list) {
                if (!CollectionUtils.isEmpty(order.getOrderMemos())) {
                    StringBuilder memoStr = new StringBuilder();
                    List<OrderMemo> orderMemos = order.getOrderMemos();
                    for (int i = 0; i < orderMemos.size(); i++) {
                        memoStr.append((i + 1) + ":");
                        memoStr.append(orderMemos.get(i).getMemo() + "\n");
                    }
                    order.setOrderMemo(memoStr.toString());
                }
            }
        }

        return list;
    }

    @Override
    public List<Car> findCarsByNumber(String carNumber, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_CAR).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("carNumber", carNumber);
        builder.append("&carNumber={carNumber}");
        if (null != companyId) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }

        List<Car> list = new ArrayList<Car>();
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public List<Order> findActivedOrdersByDriver(Long driverId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_BY_EMPLOY).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("employId", String.valueOf(driverId));
        builder.append("&employId={employId}");

        List<Order> list = new ArrayList<Order>();
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray ja = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public Long countActivedOrdersByDriver(Long driverId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.COUNT_BY_EMPLOY).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("employId", String.valueOf(driverId));
        builder.append("&employId={employId}");
        Long total = 0L;
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                total = jo.getLong("data");
            }
        }
        return total;
    }

    @Override
    public ChartYear dataForYear(Integer year, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.ORDERSTATISTICS).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        ChartYear chartYear = new ChartYear();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");

            if (code == 0) {
                if (jo.get("data") != JSONObject.NULL) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    chartYear = gson.fromJson(data.toString(), ChartYear.class);
                }

            }
        }

        return chartYear;
    }

    @Override
    public List<Order> findMonthOrder(Integer year, Integer month) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.ZHUANHEATMAP).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (month != null) {
            builder.append("&month={month}");
            kv.put("month", String.valueOf(month));
        }
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());

        List<Order> list = new ArrayList<Order>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object data = jo.get("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public ChartMonth zhuancheDataForMonth(Integer year, Integer month, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.ORDERSTATISTICSMONTH).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (month != null) {
            builder.append("&month={month}");
            kv.put("month", String.valueOf(month));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        ChartMonth chartMonth = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                if (jo.get("data") != JSONObject.NULL) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    chartMonth = gson.fromJson(data.toString(), ChartMonth.class);
                }
            }
        }
        return chartMonth;
    }

    @Override
    public List<TableOrderMonthVo> tableOrderMonth(Integer year, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.ORDERSTATISTICS).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        ChartYear chartYear = new ChartYear();
        List<TableOrderMonthVo> lists = new ArrayList<TableOrderMonthVo>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                if (jo.get("data") != JSONObject.NULL) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    chartYear = gson.fromJson(data.toString(), ChartYear.class);
                    for (ChartMonth month : chartYear.getMonths()) {
                        TableOrderMonthVo tomv = new TableOrderMonthVo();
                        tomv.setCancelAmount(month.getTotalCancelNum());
                        tomv.setFinishedAmount(month.getTotalSuccessNum());
                        tomv.setMoney(month.getTotalPrice());
                        tomv.setTime(month.getMonth());
                        lists.add(tomv);
                    }
                }
            }

        }
        return lists;
    }

    @Override
    public ChartDay zhuancheDataForDay(Integer year, Integer month, Integer day, Long companyId) {

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.ORDERSTATISTICSDAY).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (month != null) {
            builder.append("&month={month}");
            kv.put("month", String.valueOf(month));
        }
        if (day != null) {
            builder.append("&day={day}");
            kv.put("day", String.valueOf(day));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        ChartDay chartDay = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {

                if (jo.get("data") != null && jo.get("data") != JSONObject.NULL) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    chartDay = gson.fromJson(data.toString(), ChartDay.class);
                }
            }
        }

        return chartDay;
    }

    @Override
    public PageVo<MemberOrderVo> zhuanMemberOrder(Date startTime, Date endTime, Long companyId, Long gradeId, Integer type) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder sb2 = new StringBuilder();
        sb2.append(passengerApi.getPassengerBaseURL()).append(PassengerApi.QUERY_PASSENGER).append("?appKey={appKey}&page={page}&rows={rows}");

        Map<String, String> kv2 = new HashMap<String, String>();
        kv2.put("page", String.valueOf(Pager.getPage() + 1));
        kv2.put("rows", String.valueOf(Pager.getLimit()));
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv2.put("companyId", String.valueOf(companyId));
                sb2.append("&companyId={companyId}");
            }
        } else {
            kv2.put("companyId", String.valueOf(principal.getCompanyId()));
            sb2.append("&companyId={companyId}");
        }

        if (null != gradeId) {
            kv2.put("gradeId", String.valueOf(gradeId));
            sb2.append("&gradeId={gradeId}");
        }
        if (null != type) {
            kv2.put("type", String.valueOf(type));
            sb2.append("&type={type}");
        }

        String result2 = passengerApi.get(sb2.toString(), kv2, settingUtils.get());

        List<Passenger> content2 = new ArrayList<Passenger>();
        long total = 0;

        if (null != result2) {
            JSONObject jo = new JSONObject(result2);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                content2 = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
            }
        }
        StringBuilder sb1 = new StringBuilder();
        sb1.append(passengerApi.getPassengerBaseURL()).append(PassengerApi.QUERY_PASSENGER).append("?appKey={appKey}");

        Map<String, String> kv1 = new HashMap<String, String>();

        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv1.put("companyId", String.valueOf(companyId));
                sb1.append("&companyId={companyId}");
            }
        } else {
            kv1.put("companyId", String.valueOf(principal.getCompanyId()));
            sb1.append("&companyId={companyId}");
        }

        if (null != gradeId) {
            kv1.put("gradeId", String.valueOf(gradeId));
            sb1.append("&gradeId={gradeId}");
        }
        if (null != type) {
            kv1.put("type", String.valueOf(type));
            sb1.append("&type={type}");
        }

        String result1 = passengerApi.get(sb1.toString(), kv1, settingUtils.get());

        List<Passenger> findAll = new ArrayList<Passenger>();

        if (null != result1) {
            JSONObject jo = new JSONObject(result1);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                findAll = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.ZHUANMEMBERORDER).append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();

        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (null != startTime) {
            kv.put("startTime", String.valueOf(startTime.getTime()));
            sb.append("&startTime={startTime}");
        }
        if (null != endTime) {
            kv.put("endTime", String.valueOf(endTime.getTime()));
            sb.append("&endTime={endTime}");
        }

        String result = zhuanApi.get(sb.toString(), kv, settingUtils.get());
        PageVo<MemberOrderVo> content = new PageVo<MemberOrderVo>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");

                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                content = gson.fromJson(data.toString(), new TypeToken<PageVo<MemberOrderVo>>() {
                }.getType());
            }
        }

        PageVo<MemberOrderVo> vopage = new PageVo<MemberOrderVo>();
        List<MemberOrderVo> volist = new ArrayList<MemberOrderVo>();
        MemberOrderVo count = new MemberOrderVo();
        count.setName("总计");
        count.setPhone("");
        count.setCompanyName(" ");
        count.setMoney(BigDecimal.ZERO);
        for (Passenger passenger : findAll) {
            for (MemberOrderVo memberOrderVo : content.getContent()) {
                if (passenger.getId().equals(memberOrderVo.getId())) {
                    count.setFinishNums(count.getFinishNums() + memberOrderVo.getFinishNums());
                    count.setMoney(count.getMoney().add(memberOrderVo.getMoney()));
                }
            }
        }

        MemberOrderVo count2 = new MemberOrderVo();
        count2.setName("当前页总计");
        count2.setPhone("");
        count2.setCompanyName(" ");
        count2.setMoney(BigDecimal.ZERO);

        for (Passenger passenger : content2) {
            MemberOrderVo mv = new MemberOrderVo();
            mv.setId(passenger.getId());
            mv.setName(passenger.getName());
            mv.setPhone(passenger.getPhone());
            mv.setCompanyName(passenger.getCompanyName());
            for (MemberOrderVo memberOrderVo : content.getContent()) {
                if (passenger.getId().equals(memberOrderVo.getId())) {
                    mv.setFinishNums(memberOrderVo.getFinishNums());
                    mv.setMoney(memberOrderVo.getMoney());
                    break;

                }
            }
            volist.add(mv);
            count2.setFinishNums(count2.getFinishNums() + mv.getFinishNums());
            count2.setMoney(count2.getMoney().add(mv.getMoney()));
        }

        volist.add(count2);
        volist.add(count);
        vopage.setContent(volist);
        vopage.setTotalElements(findAll.size());
        return vopage;
    }

    @Override
    public PageVo<OrderFromSourceVo> orderFromSource(Date start, Date end, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.ORDERTYPESTATISTICS).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (start != null) {
            builder.append("&startDate={startDate}");
            kv.put("startDate", start.getTime() + "");
        }
        if (end != null) {
            builder.append("&endDate={endDate}");
            kv.put("endDate", end.getTime() + "");
        }

        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<OrderFromSourceVo> orderFromSourceVos = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");

                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                orderFromSourceVos = gson
                    .fromJson(data.toString(), new TypeToken<PageVo<OrderFromSourceVo>>() {
                    }.getType());
            }
        }

        return orderFromSourceVos;
    }

    @Override
    public PageVo<DriverOrderVo> zhuancheIntroduce(Long companyId, Date start, Date end) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.DRIVERACHIEVEMENT).append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (start != null) {
            kv.put("startDate", String.valueOf(start.getTime()));
            sb.append("&startDate={startDate}");
        }
        if (end != null) {
            kv.put("endDate", String.valueOf(end.getTime()));
            sb.append("&endDate={endDate}");
        }

        String result = zhuanApi.get(sb.toString(), kv, settingUtils.get());

        PageVo<DriverOrderVo> list = new PageVo<DriverOrderVo>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<PageVo<DriverOrderVo>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public PageVo<CompanyOrderVo> companyOrder(Date start, Date end) {

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.COMPANYORDERSTATISTICS).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (start != null) {
            builder.append("&startDate={startDate}");
            kv.put("startDate", start.getTime() + "");
        }
        if (end != null) {
            builder.append("&endDate={endDate}");
            kv.put("endDate", end.getTime() + "");
        }

        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<CompanyOrderVo> companyOrderVos = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");

                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                companyOrderVos = gson
                    .fromJson(data.toString(), new TypeToken<PageVo<CompanyOrderVo>>() {
                    }.getType());
            }
        }
        if (companyOrderVos != null) {
            List<Company> companys = companyMapper.selectAll();
            List<CompanyOrderVo> vos = new ArrayList<CompanyOrderVo>();
            for (Company company : companys) {
                CompanyOrderVo vo = new CompanyOrderVo();
                vo.setCompanyName(company.getAbbreviation());
                for (CompanyOrderVo vo1 : companyOrderVos.getContent()) {
                    if (vo1.getCompanyName().equals(vo.getCompanyName())) {
                        vo.setCancelNums(vo1.getCancelNums());
                        vo.setFinishNums(vo1.getFinishNums());
                        vo.setMoney(vo1.getMoney());
                        break;
                    }
                }
                vos.add(vo);
            }
            companyOrderVos.setContent(vos);
            companyOrderVos.setTotalElements(vos.size());
        }
        return companyOrderVos;
    }

    @Override
    public OrderTemp findOneTemp(Long id) {
        OrderTemp orderTemp = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDERTEMP_ONE).append("?orderId={orderId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(id));
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                orderTemp = gson.fromJson(data.toString(), OrderTemp.class);
            }
        }
        return orderTemp;
    }

/*
	public static void main(String[] args) {
	  BigDecimal prePayMoney = BigDecimal.valueOf(20.3);
	  prePayMoney = prePayMoney.subtract(prePayMoney.multiply(BigDecimal.valueOf(1).subtract(BigDecimal.valueOf((4.0 / 10)))).setScale(0,BigDecimal.ROUND_DOWN)).setScale(2,
        BigDecimal.ROUND_UP);

  }
	*/

    /***
     * $$$ 专车结算订单 now
     * @param order 订单数据 包括需要支付的金额
     * @param passenger 乘客数据
     * @param driver 司机数据
     * @param completeType 交易完成触发类型  "clickPay":司机点击按钮触发交易完成
     * @param payType 支付方式
     *                司机代付: clickPay,helppay
     *                乘客微信支付 onlinePay,weixin
     *                乘客支付宝支付 onlinePay,alipay
     *                乘客余额支付 clickPay balance
     * @param hasPayed 已支付金额
     * @param adminHandle  只能填false 不然添加订单的finishTime 和 验证订单状态
     * @return
     * @record zhyu
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Order> completeTaskNewV3(Order order, Passenger passenger, Driver driver, String completeType, String payType, BigDecimal hasPayed, boolean adminHandle) {
        Result<Order> result = new Result<Order>();

        hasPayed = BigDecimal.ZERO;

        if (!adminHandle) {
            boolean ftSuccess = zhuanApi.addFinishTime(order.getId(), settingUtils.get()).isSuccess();

            if (order.getStatus().equals(Order.ORDER_STATUS_OK) || !ftSuccess) {
                result.setSuccess(false);
                result.setErrorcode(String.valueOf(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode()));
                result.setMessage(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getMessage());
                return result;
            }
        }

        try {
            BigDecimal employProfit = BigDecimal.ZERO;//司机收益 公司收益
            BigDecimal companyProfit = BigDecimal.ZERO;

            //优惠券金额
//            BigDecimal now_couponMoney = order.getCouponMoney();
//
//            Coupon coupon = null;
//            if (null != order.getCouponId()) {
//                coupon = salesApi.findOneCoupon(order.getCouponId()).getResult();
//            }
//            Double discount = null;
//            if (null != coupon) {
//                if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DISCOUNT)) {
//                    discount = coupon.getCouponRule().getDiscount();
//                }
//            }

            //结算应支付的金额
            BigDecimal afterPayMoney = BigDecimal.ZERO;

            afterPayMoney = new BigDecimal(order.getRealPay());
            afterPayMoney = afterPayMoney.setScale(2, BigDecimal.ROUND_HALF_UP);

            if ("clickPay".equals(completeType)) {
                if ("helppay".equals(payType)) {//代付支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.helppay);
                    order.setCashMoney(order.getCashMoney().add(afterPayMoney));
                } else if ("sign".equals(payType)) {//签单支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.sign);
                    order.setSignMoney(order.getSignMoney().add(afterPayMoney));
                } else if ("balance".equals(payType)) {//余额支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.balance);
                    order.setBalanceMoney(order.getBalanceMoney().add(afterPayMoney));
                }
            } else if ("onlinePay".equals(completeType)) {
                if ("alipay".equals(payType)) {//支付宝支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.alipay);
                    order.setAlipayMoney(order.getAlipayMoney().add(afterPayMoney));
                } else if ("weixin".equals(payType)) {//微信支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.weixin);
                    order.setWeixinMoney(order.getWeixinMoney().add(afterPayMoney));
                }
            }

            List<OrderStatus> orderStatuslist = order.getStatusList();
            Date travelDate = null;
            for (OrderStatus orderStatus : orderStatuslist) {
                if (orderStatus.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                    travelDate = orderStatus.getCreated();
                    break;
                }
            }

            dealPassengerAndHelpPay(order, passenger, driver, completeType, payType, afterPayMoney);

            BigDecimal realCash = new BigDecimal(order.getRealPay());

            //优惠劵是否参与提成
            Setting setting = settingUtils.get();
            boolean couponTicheng = setting.isCouponTicheng();

            //是否使用了优惠劵
            if (order.getCouponMoney().doubleValue() > 0) {
                if (!couponTicheng) {
                    realCash = realCash.subtract(order.getCouponMoney());
                    if (realCash.compareTo(BigDecimal.ZERO) == -1) {
                        realCash = BigDecimal.ZERO;
                    }
                }
            }

            if (null != driver) {
                driver.setTodayOrders(driver.getTodayOrders() + 1);
                driver.setMonthOrders(driver.getMonthOrders() + 1);
                driver.setDriveTimes(driver.getDriveTimes() + 1);
                driverMapper.updateWhenFinishZhuanOrderByKey(driver);

                Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
                Company orderCompany = companyMapper.selectByPrimaryKey(order.getCompanyId());
                order.setRealPay(realCash.doubleValue());
                distributionProfitFromCompanyAndDriver(driver, order, travelDate, realCash, afterPayMoney, company, employProfit,
                    companyProfit, orderCompany);
                dealInfoFee(order, driver, setting);
                dealBaoxiaoRecord(order, driver, company, orderCompany);

            }

            MultiValueMap<String, String> kv = assembleParamsForPostFinishTask(order, employProfit, companyProfit);
            String resultStr = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.FINISH_TASK, kv, settingUtils.get());
            if (StringUtils.isNotBlank(resultStr)) {
                JSONObject jo = new JSONObject(resultStr);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    //结算成功保存首单免费客户信息
                    FirstOrderPassenger firstOrderPassenger = new FirstOrderPassenger();
                    firstOrderPassenger.setPassengerId(passenger.getId());
                    firstOrderPassenger.setType(FirstOrderPassenger.FREE_ORDERTYPE_ZHUANCHE);
                    firstOrderPassengerMapper.insertRecord(firstOrderPassenger);

                    result.setSuccess(true);
                    if (driver != null) {
                        zhuanApi.updateCarStatus(driver.getCarId(), Car.FREE, settingUtils.get());
                    }

                    ReactorVo rVo = new ReactorVo();
                    rVo.setOrderChannelName(order.getChannelName());
                    rVo.setOrderType(OrderType.zhuanche);
                    rVo.setPassenger(passenger);
                    rVo.setActivityEvent(ActivityEvent.orderCompleteTimes);
                    ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                    applicationEventMulticaster.multicastEvent(activityCheckEvent);

                    //推荐提成
                    IntroduceRebateEvent introduce_rebate_event = new IntroduceRebateEvent(passenger, order, new BigDecimal(order.getRealPay()), 1);
                    applicationEventMulticaster.multicastEvent(introduce_rebate_event);

                    //结算短信
                    ZhuanOrderFinishEvent zhuanOrderFinishEvent = new ZhuanOrderFinishEvent(order);
                    applicationEventMulticaster.multicastEvent(zhuanOrderFinishEvent);

                } else {
                    String message = jo.getString("message");
                    result.setSuccess(false);
                    result.setMessage(message);
                }
            } else {
                result.setSuccess(false);
                result.setMessage("内部服务器错误");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("内部服务器错误");
        }

        return result;

    }

    /**
     * 处理乘客和代付的逻辑, 包括 司机代付, 更新乘客常用地址 调用mc系统处理乘客相关逻辑, 是否扣除余额, 添加财务信息 客户扣费短信 非支付相关的 乘客属性叠加,开票金额
     *
     * @param order
     * @param passenger
     * @param driver
     * @param completeType
     * @param payType
     * @param afterPayMoney
     */
    private void dealPassengerAndHelpPay(Order order, Passenger passenger, Driver driver, String completeType, String payType, BigDecimal afterPayMoney) {
        if (null != passenger) {
            if ("clickPay".equals(completeType)) {
                if ("helppay".equals(payType)) {
                    //司机代付 司机扣除可代付金额环节

                    HelpPayRecord record = new HelpPayRecord();
                    record.setDriverId(driver.getId());
                    record.setOperateType(HelpPayRecord.DRIVER_HELPPAY);
                    record.setChangeMoney(afterPayMoney);
                    record.setMemo("司机[" + driver.getId() + "]在订单[" + order.getOrderNo() + "]代付扣款" + afterPayMoney.doubleValue() + "元");
                    record.setTradeNo(order.getOrderNo());
                    helppayService.userDriverMoney(record);

                }
                //同为 clickPay 的第二种情况 , 乘客余额支付, 实在下面的代码中传递支付金额到mc系统
            }

            //更新乘客常用地址
            if (order.getHasToPlace()) {
                Result<PassengerAddress> result_address = passengerApi.findPassengerToPlace(passenger.getId(), PassengerAddress.TYPE_ADDRESS_OTHER, settingUtils.get());
                PassengerAddress passengerAddress = result_address.getResult();
                if (null == passengerAddress) {
                    passengerApi.addPassengerToPlace(passenger.getId(), order.getEndAddress(), order.getEndLat(), order.getEndLng(), PassengerAddress.TYPE_ADDRESS_OTHER, settingUtils.get());
                } else {
                    passengerApi.updatePassengerToPlace(passenger.getId(), passengerAddress.getId(), order.getEndAddress(), order.getEndLat(), order.getEndLng(), PassengerAddress.TYPE_ADDRESS_OTHER,
                        settingUtils.get());
                }
            }

            //结算记录
            if ("clickPay".equals(completeType) || "onlinePay".equals(completeType)) {

                String memo = "";

                PassengerAccount.PayType ptype = null;
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.helppay)) {
                    memo += "结算使用代付" + afterPayMoney.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_CASH;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign)) {
                    memo += "结算使用签单支付" + afterPayMoney.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_SIGN;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                    memo += "结算使用余额支付" + afterPayMoney.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_BALANCE;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.alipay)) {
                    memo += "结算使用支付宝支付" + afterPayMoney.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_ALIPAY;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.weixin)) {
                    memo += "结算使用微信支付" + afterPayMoney.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_WEIXIN;
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.unionpay)) {
                    memo += "结算使用银联支付" + afterPayMoney.toString() + "元。";
                    ptype = PassengerAccount.PayType.PAYTYPE_UNIONPAY;
                }

                /**
                 *  调用mc系统处理乘客相关逻辑, 是否扣除余额, 添加财务信息
                 */
                PassengerAccount passengerAccount = null;
                //是否更新余额
                boolean updateBlance = false;
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign) || order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                    updateBlance = true;
                }
                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    Result<PassengerAccount> result_account = passengerApi
                        .createPassengerAccount(passenger, null, afterPayMoney.negate(), ptype, PassengerAccount.OPERATING_SYS, memo, order.getId(), order.getOrderNo(),
                            PassengerAccount.ORDER_TYPE_ZHUANCHE, null, updateBlance, true, settingUtils.get());
                    passengerAccount = result_account.getResult();
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi.findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
                    if (null != enterprise) {
                        Result<PassengerAccount> result_account = passengerApi
                            .createEnterpriseAccount(enterprise, afterPayMoney.negate(), ptype, PassengerAccount.OPERATING_SYS, memo, order.getId(), order.getOrderNo(),
                                PassengerAccount.ORDER_TYPE_ZHUANCHE, null, updateBlance, true, settingUtils.get());
                        passengerAccount = result_account.getResult();
                    }
                }
                if (updateBlance) {
                    //客户扣费短信
                    if (null != passengerAccount) {
                        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                            MemberConsumedEvent consumedEvent = new MemberConsumedEvent(passengerAccount, null);
                            applicationEventMulticaster.multicastEvent(consumedEvent);
                        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                            MemberConsumedEvent consumedEvent = new MemberConsumedEvent(passengerAccount, passenger.getPhone());
                            applicationEventMulticaster.multicastEvent(consumedEvent);
                        }
                    }
                }

            }

            /***
             * 非支付相关的 乘客属性叠加,开票金额
             */
            passenger.setMileage(passenger.getMileage() + order.getMileage());
            passenger.setDrivingNumberTimes(passenger.getDrivingNumberTimes() + 1);
            passengerApi.updatePersonal(passenger, settingUtils.get());

            if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                Enterprise enterprise = passengerApi.findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
                if (null != enterprise) {
                    enterprise.setDrivingNumberTimes(enterprise.getDrivingNumberTimes() + 1);
                    passengerApi.updateEnterpriseInfo(enterprise, settingUtils.get());
                }
            }

            BigDecimal receiptMoney = new BigDecimal(order.getRealPay()).subtract(order.getGuoluMoney()).subtract(order.getCouponMoney());
            if (receiptMoney.doubleValue() > 0) {
                passengerApi.createReceipt(passenger, receiptMoney.negate(), settingUtils.get());
            }

        }
    }

    /**
     * 为请求完成任务组装参数
     *
     * @param order
     * @param employProfit
     * @param companyProfit
     * @return
     */
    private MultiValueMap<String, String> assembleParamsForPostFinishTask(Order order, BigDecimal employProfit, BigDecimal companyProfit) {
        //更新订单
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("orderId", String.valueOf(order.getId()));

        if (null != order.getAfterPayTypeDetail()) {
            kv.add("afterPayTypeDetail", order.getAfterPayTypeDetail().toString());
        }
        kv.add("cashMoney", order.getCashMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        kv.add("signMoney", order.getSignMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        kv.add("balanceMoney", order.getBalanceMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        kv.add("alipayMoney", order.getAlipayMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        kv.add("weixinMoney", order.getWeixinMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        kv.add("unionpayMoney", order.getUnionpayMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString());

        kv.add("companyProfit", companyProfit.toString());

        kv.add("employProfit", employProfit.toString());
        if (StringUtils.isNotBlank(order.getOperating())) {
            kv.add("operating", order.getOperating());
            kv.add("mileage", String.valueOf(order.getMileage()));
            kv.add("midwayWait", String.valueOf(order.getMidwayWait()));
            kv.add("realPay", String.valueOf(order.getRealPay()));
            kv.add("runTime", String.valueOf(order.getRunTime()));
            kv.add("finishTime", String.valueOf(order.getFinishTime().getTime()));
            if (StringUtils.isNotBlank(order.getEndAddress()) && order.getEndLat() != null && order.getEndLng() != null) {
                kv.add("endAddress", order.getEndAddress());
                kv.add("endLat", String.valueOf(order.getEndLat()));
                kv.add("endLng", String.valueOf(order.getEndLng()));
            }
            if (order.getGuoluMoney() != null) {
                kv.add("guoluMoney", String.valueOf(order.getGuoluMoney()));
            }
            if (order.getBaoxiaoMoney() != null) {
                kv.add("baoxiaoMoney", String.valueOf(order.getBaoxiaoMoney()));
            }
            if (StringUtils.isNotBlank(order.getBaoxiaoMemo())) {
                kv.add("baoxiaoMemo", order.getBaoxiaoMemo());
            }
            if (StringUtils.isNotBlank(order.getEmployMemo())) {
                kv.add("employMemo", order.getEmployMemo());
            }
        }
        return kv;
    }

    /**
     * 处理司机需要的报销费用, 但是只有记录, 这个业务目前是没有用过一次的
     *
     * @param order
     * @param driver
     * @param company
     * @param orderCompany
     */
    private void dealBaoxiaoRecord(Order order, Driver driver, Company company, Company orderCompany) {
        if (StringUtils.isNotBlank(order.getOperating())) {
            if (order.getBaoxiaoMoney() != null && order.getBaoxiaoMoney().doubleValue() > 0) {
                //财务记录（司机报销）
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb = new StringBuilder();
                sb.append(OrderNumberConfig.FINANCIAL_BAOXIAO);//报销金额
                sb.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);//对象 司机
                sb.append(DateTimeUtils.DATE_FORMAT_yyyyMMdd.format(new Date()));//年月日时间
                sb.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                financialRecord.setCode(sb.toString());
                financialRecord.setCompanyId(company.getId());
                financialRecord.setCompanyName(company.getAbbreviation());
                financialRecord.setOrderCompanyId(orderCompany.getId());
                financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                financialRecord
                    .setMemo("订单号【<a target='_blank' href='/zhuanche/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】,服务人员【" + driver.getRealname() + "】报销：" + order.getBaoxiaoMemo());
                financialRecord.setMoney(order.getBaoxiaoMoney().negate());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_WAIT);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANCHE);
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_BAOXIAO);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANCHE);
                financialRecordMapper.insertRecord(financialRecord);
            }
        }
    }

    /**
     * 处理保险费
     *
     * @param order
     * @param driver
     * @param setting
     */
    private void dealInfoFee(Order order, Driver driver, Setting setting) {
        //保险费
        if (setting.getInfoFeeZhuan() != 0) {
            if (null != setting.getInfoFeeType() && setting.getInfoFeeType().equals(InfoFeeType.finishTask)) {
                driver.setVirtual(driver.getVirtual().subtract(new BigDecimal(setting.getInfoFeeZhuan())));
                driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                //扣费记录
                DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFeeZhuan()));
                driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                driverPaymentsRecord.setDriverId(driver.getId());
                driverPaymentsRecord.setDriverRealName(driver.getRealname());
                driverPaymentsRecord.setDriverUserName(driver.getUsername());
                driverPaymentsRecord.setDriverPhone(driver.getPhone());
                driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                driverPaymentsRecord.setOrderId(order.getId());
                driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANCHE);
                driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                driverPaymentsRecord.setMemo("扣除公司所得保险费/信息费" + setting.getInfoFeeZhuan() + "元。");
                driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                driverPaymentsRecord.setHappend(new Date());
                driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                //财务记录（保险费）
                Company mainCompany = companyMapper.selectMainCompany();
                DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                FinancialRecord financialRecord = new FinancialRecord();
                StringBuilder sb_f = new StringBuilder();
                sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);//保险费
                sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);//对象 服务人员
                sb_f.append(format_f.format(new Date()));//年月日时间
                sb_f.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                financialRecord.setCode(sb_f.toString());
                financialRecord.setCompanyId(mainCompany.getId());
                financialRecord.setCompanyName(mainCompany.getAbbreviation());
                financialRecord.setOrderCompanyId(mainCompany.getId());
                financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                financialRecord.setMemo("订单号【<a target='_blank' href='/zhuanche/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】保险费/信息费");
                financialRecord.setMoney(new BigDecimal(setting.getInfoFeeZhuan()));
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                financialRecord.setWho(driver.getRealname());
                financialRecord.setOrderId(order.getId());
                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANCHE);
                financialRecordMapper.insertRecord(financialRecord);

            }
        }
    }


    /***
     * 扣费提成 分配公司和司机的收益, 即公司提成
     * @param driver
     * @param order
     * @param travelDate
     * @param realCash 真实付费 算了优惠
     * @param afterPayMoney 应该付费,没算优惠
     * @param company
     * @param employProfit
     * @param companyProfit
     * @param orderCompany
     */
    private void distributionProfitFromCompanyAndDriver(Driver driver, Order order, Date travelDate, BigDecimal realCash, BigDecimal afterPayMoney, Company company, BigDecimal employProfit,
        BigDecimal companyProfit, Company orderCompany) {

        StringBuilder sbmemo = new StringBuilder();
        sbmemo.append("订单【" + order.getOrderNo() + "】，客户【" + order.getPassengerName() + "(" + order.getPassengerPhone() + ")】，");

        //后支付备注
        if (null != order.getAfterPayTypeDetail()) {
            if (order.getAfterPayTypeDetail().equals(PayTypeDetails.helppay)) {
                sbmemo.append("结算加收：代付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign)) {
                sbmemo.append("结算加收：签单支付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                sbmemo.append("结算加收：余额支付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.alipay)) {
                sbmemo.append("结算加收：支付宝支付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.weixin)) {
                sbmemo.append("结算加收：微信支付（" + afterPayMoney + "元）。");
            } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.unionpay)) {
                sbmemo.append("结算加收：银联支付（" + afterPayMoney + "元）。");
            }
        }
        boolean companyGetAll = false;//公司是否的全部
        if (null != driver.getType() && Driver.DRIVER_TYPR_PARTTIME.equals(driver.getType())) {

            DriverChoseLevelCar driverChoseLevelCar = driverChoseLevelCarMapper.selectByDriverAndCompany(driver.getId(), order.getCompanyId());

            if (null != driverChoseLevelCar) {

                DriverLevel driverLevel = null;

                if (driverChoseLevelCar.getDriverlevelId() == 0) {//始终使用本公司提成
                    DriverChoseLevelCar driverChoseLevelCar2 = driverChoseLevelCarMapper.selectByDriverAndCompany(driver.getId(), driver.getCompanyId());
                    if (null != driverChoseLevelCar2) {
                        driverLevel = driverLevelMapper.selectByPrimaryKey(driverChoseLevelCar2.getDriverlevelId());
                    }
                } else {
                    driverLevel = driverLevelMapper.selectByPrimaryKey(driverChoseLevelCar.getDriverlevelId());
                }

                DriverLevelDetail detail = null;
                DriverLevelMoneyTimeDetail moneyTimeDetail = null;

                if (null != driverLevel) {
                    if (driverLevel.getType().equals(0)) {
                        driverLevel.setDriverLevelDetails(driverLevelDetailMapper.selectByDriverLevel(driverLevel.getId()));
                        if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                            detail = driverLevel.getDeatil(order.getServerTime());
                        } else if (driverLevel.getTimePoint().equals(TimePoint.startDrive)) {
                            detail = driverLevel.getDeatil(travelDate);
                        } else if (driverLevel.getTimePoint().equals(TimePoint.finishTime)) {
                            detail = driverLevel.getDeatil(new Date());
                        }
                    } else if (driverLevel.getType().equals(1)) {
                        driverLevel.setDriverLevelMoneyTimeDetails(driverLevelMoneyTimeDetailMapper.selectByDriverLevel(driverLevel.getId()));
                        if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                            moneyTimeDetail = driverLevel.getMoneyTimeDeatil(order.getServerTime());
                        } else if (driverLevel.getTimePoint().equals(TimePoint.startDrive)) {
                            moneyTimeDetail = driverLevel.getMoneyTimeDeatil(travelDate);
                        } else if (driverLevel.getTimePoint().equals(TimePoint.finishTime)) {
                            moneyTimeDetail = driverLevel.getMoneyTimeDeatil(new Date());
                        }
                    }
                }

                if (null != detail) {

                    BigDecimal money = BigDecimal.ZERO;
                    BigDecimal companyMoney = BigDecimal.ZERO;

                    if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
                        if (realCash.compareTo(detail.getMinCommission()) == -1) {
                            money = realCash.subtract(detail.getLowCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            companyMoney = detail.getLowCommission();
                            if (money.doubleValue() < 0) {
                                money = BigDecimal.ZERO;
                                companyMoney = realCash;
                            }
                            sbmemo.append("按照【低于" + detail.getMinCommission() + "元公司得" + detail.getLowCommission() + "元】方式，服务人员得" + money + "元。");
                        } else {
                            money = realCash.multiply(new BigDecimal(100).subtract(detail.getCommission())).divide(new BigDecimal(100));
                            companyMoney = realCash.subtract(money);
                            sbmemo.append("按照【" + detail.getCommission() + "%公司所得】提成方式。");
                        }
                    } else if (detail.getDriverLevelType().equals(DriverLevelType.guding)) {
                        if (realCash.compareTo(detail.getMinMoney()) == -1) {
                            money = realCash.subtract(detail.getLowMoney()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            companyMoney = detail.getLowMoney();
                            if (money.doubleValue() < 0) {
                                money = BigDecimal.ZERO;
                                companyMoney = realCash;
                            }
                            sbmemo.append("按照【低于" + detail.getMinMoney() + "元公司得" + detail.getLowMoney() + "元】方式，服务人员得" + money + "元。");
                        } else {

                            sbmemo.append("按照【" + detail.getMoney() + "元公司所得】提成方式。");

                            if (realCash.compareTo(detail.getMoney()) == -1) {
                                money = BigDecimal.ZERO;
                                companyMoney = realCash;
                            } else {
                                money = realCash.subtract(detail.getMoney());
                                companyMoney = detail.getMoney();
                            }

                        }
                    }

                    employProfit = money;
                    companyProfit = companyMoney;

                    driver.setVirtual(driver.getVirtual().add(money));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(money);
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANCHE);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo(sbmemo.toString());
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    //公司财务
                    String companyMemo = "订单号【<a target='_blank' href='/zhuanche/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】收入。";

                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb = new StringBuilder();
                    sb.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                    sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                    sb.append(DateTimeUtils.DATE_FORMAT_yyyyMMdd.format(new Date()));//年月日时间
                    sb.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                    financialRecord.setCode(sb.toString());
                    financialRecord.setCompanyId(company.getId());
                    financialRecord.setCompanyName(company.getAbbreviation());
                    financialRecord.setOrderCompanyId(orderCompany.getId());
                    financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                    financialRecord.setMemo(companyMemo + driverPaymentsRecord.getMemo());
                    financialRecord.setMoney(companyMoney);
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(order.getPassengerName());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANCHE);
                    financialRecordMapper.insertRecord(financialRecord);

                } else if (null != moneyTimeDetail) {//复杂提成

                    BigDecimal money = BigDecimal.ZERO;
                    BigDecimal companyMoney = BigDecimal.ZERO;//公司所得金额

                    if (!CollectionUtils.isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                        for (DriverLevelMoneyDetail dlmd : moneyTimeDetail.getDriverLevelMoneyDetails()) {
                            if (realCash.doubleValue() >= dlmd.getFromMoney().doubleValue()) {

                                BigDecimal _money = BigDecimal.ZERO;
                                if (realCash.doubleValue() >= dlmd.getToMoney().doubleValue()) {
                                    _money = dlmd.getToMoney().subtract(dlmd.getFromMoney());
                                } else {
                                    _money = realCash.subtract(dlmd.getFromMoney());
                                }

                                if (dlmd.getDriverLevelMoneyType().equals(DriverLevelMoneyType.guding)) {//固定
                                    BigDecimal tcMoney = dlmd.getMoney().multiply(new BigDecimal((int) (_money.doubleValue() / dlmd.getMoneyUnit().doubleValue())));
                                    companyMoney = companyMoney.add(tcMoney);
                                } else if (dlmd.getDriverLevelMoneyType().equals(DriverLevelMoneyType.ticheng)) {//比例
                                    BigDecimal tcMoney = _money.multiply(dlmd.getCommission()).divide(new BigDecimal(100));
                                    companyMoney = companyMoney.add(tcMoney);
                                }
                            }
                        }
                    }

                    if (realCash.compareTo(companyMoney) == -1) {
                        companyMoney = realCash;
                        money = BigDecimal.ZERO;
                        sbmemo.append("金额不足，公司实际提成" + companyMoney + "元。");
                    } else {
                        money = realCash.subtract(companyMoney);
                    }

                    employProfit = money;
                    companyProfit = companyMoney;

                    driver.setVirtual(driver.getVirtual().add(money));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(money);
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANCHE);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo(sbmemo.toString());
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    //公司财务
                    String companyMemo = "订单号【<a target='_blank' href='/zhuanche/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】收入。";

                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb = new StringBuilder();
                    sb.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                    sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                    sb.append(DateTimeUtils.DATE_FORMAT_yyyyMMdd.format(new Date()));//年月日时间
                    sb.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                    financialRecord.setCode(sb.toString());
                    financialRecord.setCompanyId(company.getId());
                    financialRecord.setCompanyName(company.getAbbreviation());
                    financialRecord.setOrderCompanyId(orderCompany.getId());
                    financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                    financialRecord.setMemo(companyMemo + driverPaymentsRecord.getMemo());
                    financialRecord.setMoney(companyMoney);
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(order.getPassengerName());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANCHE);
                    financialRecordMapper.insertRecord(financialRecord);

                } else {
                    companyGetAll = true;
                }

            } else {
                companyGetAll = true;
            }
        } else {
            companyGetAll = true;
        }

        //公司得全部
        if (companyGetAll) {

            companyProfit = realCash;

            String companyMemo = "订单号【<a target='_blank' href='/zhuanche/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】收入。";

            FinancialRecord financialRecord = new FinancialRecord();
            StringBuilder sb = new StringBuilder();
            sb.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
            sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
            sb.append(DateTimeUtils.DATE_FORMAT_yyyyMMdd.format(new Date()));//年月日时间
            sb.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
            financialRecord.setCode(sb.toString());
            financialRecord.setCompanyId(company.getId());
            financialRecord.setCompanyName(company.getAbbreviation());
            financialRecord.setOrderCompanyId(orderCompany.getId());
            financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
            financialRecord.setMemo(companyMemo + sbmemo.toString());
            financialRecord.setMoney(realCash);
            financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
            financialRecord.setWho(order.getPassengerName());
            financialRecord.setOrderId(order.getId());
            financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
            financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANCHE);
            financialRecordMapper.insertRecord(financialRecord);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Order> confirmTask(Order order, String xml) {

        Result<Order> result = new Result<Order>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("orderId", String.valueOf(order.getId()));

        kv.add("realPay", String.valueOf(order.getRealPay()));

        kv.add("guoluMoney", String.valueOf(order.getGuoluMoney()));

        kv.add("yuanchengMoney", String.valueOf(order.getYuanchengMoney()));

        kv.add("otherMoney", String.valueOf(order.getOtherMoney()));

        kv.add("couponMoney", String.valueOf(order.getCouponMoney()));

        if (null != order.getPrePayTypeDetail()) {
            kv.add("prePayTypeDetail", String.valueOf(order.getPrePayTypeDetail()));
        }

        if (null != order.getDiscount()) {
            kv.add("discount", String.valueOf(order.getDiscount()));
        }

        if (null != order.getStartPrice()) {
            kv.add("startPrice", String.valueOf(order.getStartPrice()));
        }

        if (null != order.getMileagePrice()) {
            kv.add("mileagePrice", String.valueOf(order.getMileagePrice()));
        }

        if (null != order.getRunTimePrice()) {
            kv.add("runTimePrice", String.valueOf(order.getRunTimePrice()));
        }

        if (null != order.getWaitPrice()) {
            kv.add("waitPrice", String.valueOf(order.getWaitPrice()));
        }

        kv.add("mileage", String.valueOf(order.getMileage()));

        kv.add("midwayWait", String.valueOf(order.getMidwayWait()));

        kv.add("runTime", String.valueOf(order.getRunTime()));

        if (StringUtils.isNotBlank(xml)) {
            kv.add("xml", xml);
        }

        if (StringUtils.isNotBlank(order.getMemo())) {
            kv.add("memo", order.getMemo());
        }
        if (null != order.getJustKilometres()) {
            kv.add("justKilometres", String.valueOf(order.getJustKilometres()));
        }
        if (null != order.getJustMoney()) {
            kv.add("justMoney", String.valueOf(order.getJustMoney()));
        }

        if (StringUtils.isNotBlank(order.getEndAddress()) && null != order.getEndLng() && null != order.getEndLat()) {
            kv.add("endAddress", order.getEndAddress());

            kv.add("endLat", String.valueOf(order.getEndLat()));

            kv.add("endLng", String.valueOf(order.getEndLng()));
        }

        String resultStr = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.CONFIRM_TASK, kv, settingUtils.get());

        logger.info("resultStr:{}", resultStr);
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                result.setSuccess(true);
            } else {
                String message = jo.getString("message");
                result.setSuccess(false);
                result.setMessage(message);
            }
        } else {
            result.setSuccess(false);
            result.setMessage("未知错误");
        }

        return result;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Order> confirmTaskV4(Order order, Driver driver) {

        Result<Order> result = new Result<Order>();

        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null, driver.getId());

        return result;

    }

    @Override
    public PageVo<DriverOrderDetailVo> driverOrderDetailCount(Long driverId, Date start, Date end) {

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.DRIVERORDERDETAILCOUNT).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (driverId != null) {
            kv.put("driverId", driverId + "");
            builder.append("&driverId={driverId}");
        }
        if (start != null) {
            kv.put("startDate", start.getTime() + "");
            builder.append("&startDate={startDate}");
        }
        if (end != null) {
            kv.put("endDate", end.getTime() + "");
            builder.append("&endDate={endDate}");
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<DriverOrderDetailVo> page = new PageVo<DriverOrderDetailVo>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Long couont = jo.optLong("data", 0L);
                page.setTotalElements(couont);
            }
        }

        return page;
    }

    @Override
    public Result<Map<String, Object>> batchCreate(String data) {
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("cars", data);
        Result<Map<String, Object>> resultData = new Result<>();
        String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.BATCHCREATE, kv, settingUtils.get());
        PageVo<DriverOrderDetailVo> page = new PageVo<DriverOrderDetailVo>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                resultData.setSuccess(true);
                JSONObject data1 = jo.getJSONObject("data");
                Map<String, Object> mv = new HashMap<>();
                mv.put("carNumber", data1.optLong("carNumber", 0L));
                mv.put("typeNumber", data1.optLong("typeNumber", 0L));
                mv.put("rows", data1.optLong("rows", 0L));

                resultData.setResult(mv);
            } else {
                resultData.setSuccess(false);
            }
        }
        return resultData;
    }

    @Override
    public Page<Car> findCarByIds(Long[] ids, Integer page, Integer limit) {
        Pageable pageable = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_CAR_BY_IDS).append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        if (page != null && limit != null) {
            kv.put("page", String.valueOf(page + 1));
            kv.put("rows", String.valueOf(limit));
            builder.append("&page={page}&rows={rows}");
            pageable = new PageRequest(page, limit);
        } else {
            pageable = new PageRequest(1, ids.length);
        }

        if (ids != null && ids.length > 0) {
            kv.put("ids", StringUtils.join(ids, ","));
            builder.append("&ids={ids}");
        }

        List<Car> list = new ArrayList<Car>();
        long total = 0;
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        return new PageImpl<Car>(list, pageable, total);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<PayRecordOrder> createPayRecordOrder(PayRecordOrder payRecordOrder) {
        Result<PayRecordOrder> result = new Result<PayRecordOrder>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("orderId", String.valueOf(payRecordOrder.getOrderId()));

        kv.add("money", payRecordOrder.getMoney().toString());

        kv.add("payRecordTypeOrder", payRecordOrder.getPayRecordTypeOrder().toString());

        String resultStr = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.CREATE_PAYRECORDORDER, kv, settingUtils.get());
        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                PayRecordOrder pr = gson.fromJson(data.toString(), PayRecordOrder.class);
                result.setResult(pr);
                result.setSuccess(true);
            } else {
                String message = jo.getString("message");
                result.setSuccess(false);
                result.setMessage(message);
            }
        } else {
            result.setSuccess(false);
            result.setMessage("未知错误");
        }

        return result;
    }

    @Override
    public PayRecordOrder findOnePayRecordOrder(Long id) {
        PayRecordOrder payRecordOrder = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_PAYRECORDORDER_ONE).append("?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(id));
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                payRecordOrder = gson.fromJson(data.toString(), PayRecordOrder.class);
            }
        }
        return payRecordOrder;
    }

    @Override
    public Result<PayRecordOrder> payRecordOrderTreatment(PayRecordOrder payRecordOrder) {

        Result<PayRecordOrder> result = new Result<PayRecordOrder>();

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.TREATMENT_PAYRECORDORDER).append("?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(payRecordOrder.getId()));

        String resultStr = zhuanApi.put(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
            result.setSuccess(false);
        } else {
            result.setSuccess(true);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Order> fillOrder(Order order, Driver driver, CarType carType) {

        Result<Order> result = new Result<Order>();

        Double longitude = order.getStartLng();
        Double latitude = order.getStartLat();

        // 根据客户电话查询客户
        Result<Passenger> result_p = passengerApi.findOnePassengerByPhone(order.getPassengerPhone(), settingUtils.get());
        Passenger passenger = result_p.getResult();
        if (null != passenger) {
            // 老客户 更新位置
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            if (!StringUtils.isBlank(order.getPassengerName()) && StringUtils.isBlank(passenger.getName())) {
                passenger.setName(order.getPassengerName());
                passengerApi.updatePersonal(passenger, settingUtils.get());
            }
        } else {
            // 新客户
            passenger = new Passenger();
            passenger.setName(order.getPassengerName());
            passenger.setPhone(order.getPassengerPhone());
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_BUDAN);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
            passenger.setCompanyId(company.getId());
            passenger.setCompanyName(company.getAbbreviation());

            Result<Passenger> result_p2 = passengerApi.createPersonal(passenger, settingUtils.get());
            if (result_p2.isSuccess()) {
                passenger = result_p2.getResult();
            } else {
                result.setMessage(result_p2.getMessage());
                result.setSuccess(false);
                return result;
            }
        }

        String memo = "";

        if (passenger.isInBlackList()) {
            memo = "黑名单客户";
        }

        Company driverCompany = companyMapper.selectByPrimaryKey(driver.getCompanyId());

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("passengerId", String.valueOf(passenger.getId()));
        kv.add("passengerName", passenger.getName());
        kv.add("passengerPhone", passenger.getPhone());
        kv.add("companyId", String.valueOf(driverCompany.getId()));
        kv.add("companyName", driverCompany.getAbbreviation());
        kv.add("carTypeId", String.valueOf(carType.getId()));
        kv.add("channelName", Order.ORDER_TYPE_BUDAN.toString());
        kv.add("startAddress", order.getStartAddress());
        kv.add("startLat", String.valueOf(order.getStartLat()));
        kv.add("startLng", String.valueOf(order.getStartLng()));
        kv.add("serverTime", String.valueOf(order.getServerTime().getTime()));

        kv.add("employId", String.valueOf(driver.getId()));
        kv.add("employCompanyId", String.valueOf(driver.getCompanyId()));
        kv.add("employName", driver.getName());
        kv.add("employPhone", driver.getPhone());
        kv.add("employNo", driver.getUsername());
        kv.add("employPhoto", driver.getPhoto());
        kv.add("employScore", String.valueOf(driver.getStarLevel()));

        if (StringUtils.isNotBlank(memo)) {
            kv.add("memo", memo);
        }

        String resultStr = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.FILL_ORDER, kv, settingUtils.get());

        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                Order o = gson.fromJson(data.toString(), Order.class);
                result.setResult(this.findOne(o.getId()));
                result.setSuccess(true);
            } else {
                String message = jo.getString("message");
                result.setSuccess(false);
                result.setMessage(message);
                return result;
            }
        } else {
            result.setSuccess(false);
            result.setMessage("内部服务器错误");
            return result;
        }

        // 设置服务人员为忙碌
        driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_BUSY, Driver.DRIVER_JOBSTATUS_ZHUANCHE, driver.getId());

        // 扣费
        Setting setting = settingUtils.get();

        if (null != driver) {
            if (setting.getInfoFeeZhuan() != 0) {
                if (null != setting.getInfoFeeType() && setting.getInfoFeeType().equals(InfoFeeType.acceptTask)) {
                    driver.setVirtual(driver.getVirtual().subtract(new BigDecimal(setting.getInfoFeeZhuan())));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                    // 扣费记录
                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFeeZhuan()));
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANCHE);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo("扣除公司所得保险费/信息费" + setting.getInfoFeeZhuan() + "元。");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    // 财务记录（保险费）
                    Company mainCompany = companyMapper.selectMainCompany();
                    DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb_f = new StringBuilder();
                    sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                    sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象
                    // 服务人员
                    sb_f.append(format_f.format(new Date()));// 年月日时间
                    sb_f.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                    financialRecord.setCode(sb_f.toString());
                    financialRecord.setCompanyId(mainCompany.getId());
                    financialRecord.setCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setOrderCompanyId(mainCompany.getId());
                    financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setMemo("订单号【<a target='_blank' href='/zhuanche/detail/" + order.getId() + "'>" + order.getOrderNo()
                        + "</a>】保险费/信息费");
                    financialRecord.setMoney(new BigDecimal(setting.getInfoFeeZhuan()));
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(driver.getRealname());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANCHE);
                    financialRecordMapper.insertRecord(financialRecord);
                }
            }
        }

        result.setSuccess(true);
        return result;
    }

    @Override
    public PageVo<DriverOrderDetailVo> driverOrderDetail(Long driverId, Date start, Date end) {

        return driverOrderDetailFunc(driverId, start, end, Pager.getPage() + 1, Pager.getLimit());

    }

    @Override
    public PageVo<DriverOrderDetailVo> driverOrderDetail2(Long driverId, Date start, Date end) {

        return driverOrderDetailFunc(driverId, start, end, null, null);

    }

    private PageVo<DriverOrderDetailVo> driverOrderDetailFunc(Long driverId, Date start, Date end, Integer page, Integer rows) {

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.DRIVERORDERDETAILVO).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (null != page) {
            kv.put("page", String.valueOf(page));
            builder.append("&page={page}");
        }
        if (null != rows) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (driverId != null) {
            kv.put("driverId", driverId + "");
            builder.append("&driverId={driverId}");
        }
        if (start != null) {
            kv.put("startDate", start.getTime() + "");
            builder.append("&startDate={startDate}");
        }
        if (end != null) {
            kv.put("endDate", end.getTime() + "");
            builder.append("&endDate={endDate}");
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<DriverOrderDetailVo> pagevo = new PageVo<DriverOrderDetailVo>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                pagevo = gson
                    .fromJson(data.toString(), new TypeToken<PageVo<DriverOrderDetailVo>>() {
                    }.getType());
            }
        }

        return pagevo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void acceptInfoFee(Driver driver, Order order) {

        if (null != driver) {
            Setting setting = settingUtils.get();
            if (setting.getInfoFeeZhuan() != 0) {
                if (null != setting.getInfoFeeType() && setting.getInfoFeeType().equals(InfoFeeType.acceptTask)) {
                    driver.setVirtual(driver.getVirtual().subtract(new BigDecimal(setting.getInfoFeeZhuan())));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                    // 扣费记录
                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFeeZhuan()));
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANCHE);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo("扣除公司所得保险费/信息费" + setting.getInfoFeeZhuan() + "元。");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    // 财务记录（保险费）
                    Company mainCompany = companyMapper.selectMainCompany();
                    DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb_f = new StringBuilder();
                    sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);// 保险费
                    sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);// 对象
                    // 服务人员
                    sb_f.append(format_f.format(new Date()));// 年月日时间
                    sb_f.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));// 流水号
                    financialRecord.setCode(sb_f.toString());
                    financialRecord.setCompanyId(mainCompany.getId());
                    financialRecord.setCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setOrderCompanyId(mainCompany.getId());
                    financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setMemo("订单号【<a target='_blank' href='/zhuanche/detail/" + order.getId() + "'>" + order.getOrderNo()
                        + "</a>】保险费/信息费");
                    financialRecord.setMoney(new BigDecimal(setting.getInfoFeeZhuan()));
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(driver.getRealname());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANCHE);
                    financialRecordMapper.insertRecord(financialRecord);
                }
            }

        }

    }

    @Override
    public void updateCarStatus(Long carId, Integer i) {

        zhuanApi.updateCarStatus(carId, i, settingUtils.get());
    }

    @Override
    public long countFinishedByPassengerAndFinishTime(Long passengerId, String orderFromSources, Date startDate, Date endDate) {

        return zhuanApi.countFinishedByPassengerAndFinishTime(passengerId, orderFromSources, startDate, endDate, settingUtils.get());

    }

    @Override
    public long countActiveByPassenger(Long passengerId) {
        return zhuanApi.countActiveByPassenger(passengerId, settingUtils.get());
    }

    @Override
    public Page<Order> findByDriverAndFinishTime(Long employId, Date start, Date end, Integer page, Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_FINISHED_BY_EMPLOY).append("?appKey={appKey}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(page + 1));
        kv.put("rows", String.valueOf(limit));

        kv.put("employId", String.valueOf(employId));
        builder.append("&employId={employId}");

        if (null != start) {
            kv.put("start", String.valueOf(start.getTime()));
            builder.append("&start={start}");
        }
        if (null != end) {
            kv.put("end", String.valueOf(end.getTime()));
            builder.append("&end={end}");
        }

        List<Order> list = new ArrayList<Order>();
        long total = 0;
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
            try {
                //排序
                Collections.sort(list, new Comparator() {
                    @Override
                    public int compare(Object o1, Object o2) {
                        Order stu1 = (Order) o1;
                        Order stu2 = (Order) o2;
                        if (stu1.getFinishTime().getTime() > stu2.getFinishTime().getTime()) {
                            return -1;
                        } else if (stu1.getFinishTime().getTime() == stu2.getFinishTime().getTime()) {
                            return 0;
                        } else {
                            return 1;
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new PageImpl<Order>(list, pageable, total);
    }

    @Override
    public Map<String, Object> findRate(Long driverid, Integer page, Integer limit) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDEREVIEW).append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (driverid != null) {
            kv.put("driverId", driverid + "");
            builder.append("&driverId={driverId}");
        }
        List<OrderReview> list = new ArrayList<OrderReview>();

        long total = 0;
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();

                list = gson.fromJson(ja.toString(), new TypeToken<List<OrderReview>>() {
                }.getType());
            }
        }
        List<Rate> data = new LinkedList<Rate>();
        for (OrderReview or : list) {
            Rate r = new Rate();
            r.setContent(or.getContent());
            r.setCreated(or.getCreated());
            r.setDriverId(or.getEmployId());
            r.setDriverName(or.getEmployName());
            r.setId(or.getId());
            r.setManager(false);
            r.setMemberId(or.getPassengerId());
            r.setMemberName(or.getPassengerName());
            r.setOrderId(or.getOrderId());
            r.setOrderNumber(or.getOrderNo());
            r.setStarLevel(or.getScore().floatValue());
            r.setUpdated(or.getUpdated());
            data.add(r);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", total);
        map.put("data", data);
        return map;
    }

    @Override
    public Rate findRateOne(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDEREVIEW_ONE).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (id != null) {
            kv.put("id", id + "");
            builder.append("&id={id}");
        }
        OrderReview or = null;
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                or = gson.fromJson(data.toString(), new TypeToken<OrderReview>() {
                }.getType());
            }
        }
        Rate r = null;
        if (or != null) {
            r = new Rate();
            r.setContent(or.getContent());
            r.setCreated(or.getCreated());
            r.setDriverId(or.getEmployId());
            r.setDriverName(or.getEmployName());
            r.setId(or.getId());
            r.setManager(false);
            r.setMemberId(or.getPassengerId());
            r.setMemberName(or.getPassengerName());
            r.setOrderId(or.getOrderId());
            r.setOrderNumber(or.getOrderNo());
            r.setStarLevel(or.getScore().floatValue());
            r.setUpdated(or.getUpdated());
        }
        return r;
    }

    @Override
    public void deleteRateOne(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.DELETE_ORDEREVIEW).append("?appKey={appKey}");
        Map<String, String> kv = new LinkedHashMap<String, String>();
        if (id != null) {
            kv.put("id", id + "");
            builder.append("&id={id}");
        }
        zhuanApi.delete(builder.toString(), kv, settingUtils.get());
    }

    /**
     * 修改订单金额
     */
    @Override
    public Result<Order> updateRealMoney(Order order, BigDecimal couponMoney, BigDecimal cashMoney, BigDecimal signMoney, BigDecimal balanceMoney,
        BigDecimal alipayMoney, BigDecimal weixinMoney, BigDecimal driverMoney, BigDecimal memberMoney, BigDecimal wxMoney, String content) {
        Result<Order> result = new Result<Order>();
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();
        if (null == couponMoney) {
            couponMoney = BigDecimal.ZERO;
        }
        if (null == cashMoney) {
            cashMoney = BigDecimal.ZERO;
        }
        if (null == signMoney) {
            signMoney = BigDecimal.ZERO;
        }
        if (null == balanceMoney) {
            balanceMoney = BigDecimal.ZERO;
        }
        if (null == alipayMoney) {
            alipayMoney = BigDecimal.ZERO;
        }
        if (null == weixinMoney) {
            weixinMoney = BigDecimal.ZERO;
        }

        final BigDecimal newCash = couponMoney.add(cashMoney).add(signMoney).add(balanceMoney).add(alipayMoney).add(weixinMoney);

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanApi.getZhuanBaseURL());
        sb.append(ZhuanApi.UPDATE_REALMONEY);

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("orderId", String.valueOf(order.getId()));
        kv.add("couponMoney", String.valueOf(couponMoney));
        kv.add("cashMoney", String.valueOf(newCash));
        kv.add("signMoney", String.valueOf(signMoney));
        kv.add("balanceMoney", String.valueOf(balanceMoney));
        kv.add("alipayMoney", String.valueOf(alipayMoney));
        kv.add("weixinMoney", String.valueOf(weixinMoney));
        kv.add("operator", operator);
        kv.add("content", content);

        zhuanApi.postMultiValueMap(sb.toString(), kv, settingUtils.get());

        Driver driver = driverMapper.selectByPrimaryKey(order.getEmployId());

        if (driverMoney.compareTo(BigDecimal.ZERO) != 0) {
            driver.setVirtual(driver.getVirtual().add(driverMoney));
            driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
            driverPaymentsRecord.setMoney(driverMoney.abs());
            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
            driverPaymentsRecord.setDriverId(driver.getId());
            driverPaymentsRecord.setDriverRealName(driver.getRealname());
            driverPaymentsRecord.setDriverUserName(driver.getUsername());
            driverPaymentsRecord.setDriverPhone(driver.getPhone());
            driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
            driverPaymentsRecord.setOrderId(order.getId());
            driverPaymentsRecord.setOrderNumber(order.getOrderNo());
            driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANCHE);
            driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
            driverPaymentsRecord.setMemo("【" + principal.getUsername() + "】将订单金额由￥" + order.getRealPay() + "修改为￥" + newCash + "，原因：" + content
                + "，订单号【<a target='_blank' href='/zhuanche/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】");
            driverPaymentsRecord.setOperating(principal.getUsername());
            if (driverMoney.doubleValue() > 0) {
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_MODIFY);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
            } else {
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMED_TYPE_MODIFY);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
            }
            driverPaymentsRecord.setHappend(new Date());
            driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

        }
        if (memberMoney.compareTo(BigDecimal.ZERO) != 0) {
            Result<Passenger> result_p = passengerApi.findOnePassenger(order.getPassengerId(), settingUtils.get());
            Passenger passenger = result_p.getResult();

            if (null != passenger) {

                String memo = "【" + principal.getUsername() + "】将订单金额由￥" + order.getRealPay() + "修改为￥" + newCash + "，原因：" + content
                    + "，订单号【<a target='_blank' href='/zhuanche/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】";

                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    passengerApi.createPassengerAccount(passenger, null, memberMoney, PassengerAccount.PayType.CASH_MODIFY, principal.getUsername(),
                        memo, order.getId(), order.getOrderNo(), PassengerAccount.ORDER_TYPE_ZHUANCHE, null, true, false, settingUtils.get());
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi.findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
                    if (null != enterprise) {
                        passengerApi.createEnterpriseAccount(enterprise, memberMoney, PassengerAccount.PayType.CASH_MODIFY, principal.getUsername(),
                            memo, order.getId(), order.getOrderNo(), PassengerAccount.ORDER_TYPE_ZHUANCHE, null, true, false, settingUtils.get());
                    }
                }

            }
        }
        BigDecimal financialCash = driverMoney.multiply(new BigDecimal(-1));

        FinancialRecord financialRecord = financialRecordMapper.selectByOrderIdAndOrderType(order.getId(),
            FinancialRecord.FINANCIALRECORD_TYPE_SHOURU, FinancialRecord.ORDER_TYPE_ZHUANCHE);
        if (null != financialRecord) {
            BigDecimal oldMoney = financialRecord.getMoney();
            financialRecord.setMoney(financialRecord.getMoney().add(financialCash));
            financialRecord.setMemo(financialRecord.getMemo() + " ; " + "<br/>【" + principal.getUsername() + "】将订单金额由￥" + order.getRealPay() + "修改为￥"
                + newCash + "，原因：" + content + "，修改前￥" + oldMoney + "，修改后￥" + financialRecord.getMoney() + "");
            financialRecordMapper.updateByPrimaryKey(financialRecord);
        }
        final String clientPhone = order.getPassengerPhone();
        final String orderNumber = order.getOrderNo();
        final Long companyId = order.getCompanyId();
        Company orderCompany = companyMapper.selectByPrimaryKey(companyId);
        Company mainCompany = companyMapper.selectMainCompany();
        Setting setting = settingUtils.get();
        if (!mainCompany.getId().equals(orderCompany.getId()) && setting.isSmsMainCompany()) {
            orderCompany = mainCompany;
        }
        final Company finalCompany = orderCompany;

        try {
            SmsTemplet templet = smsService.findByAlias(finalCompany.getId(), SmsType.modifyZhuancheCash);

            if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                smsService.sendSms(clientPhone, "modifyZhuancheCash", "{\"订单号\":\"" + "***" + orderNumber.substring(8) + "\",\"收费金额\":\"" + newCash
                    + "" + "\",\"投诉建议电话\":\"" + finalCompany.getTelephone() + "\"}", finalCompany.getId(), 0, finalCompany.getSignName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        result.setSuccess(true);

        result.setMessage("修改金额成功");
        return result;
    }

    @Override
    public List<Order> findOrderFinishedBycompanyId(Long companyId, Date start, Date end) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.QUERY_ORDER).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (start != null) {
            builder.append("&startFinishTime={startFinishTime}");
            kv.put("startFinishTime", start.getTime() + "");
        }
        if (end != null) {
            builder.append("&endFinishTime={endFinishTime}");
            kv.put("endFinishTime", end.getTime() + "");
        }

        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        List<Order> orderFromSourceVos = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject obj = jo.getJSONObject("data");
                JSONArray data = obj.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                orderFromSourceVos = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }

        return orderFromSourceVos;
    }

    @Override
    public long countNotPayByPassenger(Long passengerId) {
        Long notPayAmounts = 0L;
        try {
            StringBuilder builder = new StringBuilder();
            builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.COUNT_NOTPAY_BY_PASSENGER).append("?appKey={appKey}");
            Map<String, String> kv = new HashMap(2);
            builder.append("&passengerId={passengerId}");
            builder.append("&type={type}");
            kv.put("passengerId", String.valueOf(passengerId));
            kv.put("type", "notPay");
            String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    Long total = jo.getLong("data");
                    notPayAmounts = total;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return notPayAmounts;
    }

    @Override
    public long countNotFinishedByPassenger(Long passengerId) {

        Long notFinishedAmounts = 0L;

        try {
            StringBuilder builder = new StringBuilder();
            builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.COUNT_NOTFINISHED_BY_PASSENGER).append("?appKey={appKey}");
            Map<String, String> kv = new HashMap<String, String>();
            builder.append("&passengerId={passengerId}");
            kv.put("passengerId", String.valueOf(passengerId));
            String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    Long total = jo.getLong("data");
                    notFinishedAmounts = total;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return notFinishedAmounts;
    }

    @Override
    public long countTodayOrderByPassenger(Long passengerId) {

        Long todayAmounts = 0L;

        try {
            StringBuilder builder = new StringBuilder();
            builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.COUNT_TODAYORDER_BY_PASSENGER).append("?appKey={appKey}");
            Map<String, String> kv = new HashMap<String, String>();
            builder.append("&passengerId={passengerId}");
            kv.put("passengerId", String.valueOf(passengerId));
            String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONArray data = jo.getJSONArray("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    todayAmounts = gson.fromJson(data.toString(), Long.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return todayAmounts;
    }

    @Override
    public List<Order> findReward(Long driverId, BigDecimal lowestMoney, Date start, Date end) {
        List<Order> list = new ArrayList<Order>();

        try {
            StringBuilder builder = new StringBuilder();
            builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.FIND_REWARD).append("?appKey={appKey}");
            Map<String, String> kv = new HashMap<String, String>();

            builder.append("&employId={employId}");
            kv.put("employId", String.valueOf(driverId));

            builder.append("&money={money}");
            kv.put("money", String.valueOf(lowestMoney));

            if (null != start) {
                builder.append("&startTime={startTime}");
                kv.put("startTime", String.valueOf(start.getTime()));
            }

            if (null != end) {
                builder.append("&endTime={endTime}");
                kv.put("endTime", String.valueOf(end.getTime()));
            }

            String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONArray data = jo.getJSONArray("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                    }.getType());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    @Override
    public List<OrderTemp> queryByGroupId(Long groupId) {
        List<OrderTemp> list = new ArrayList<OrderTemp>();
        try {
            String url = zhuanApi.getZhuanBaseURL() + ZhuanApi.QUERYBYGROUPID + "?groupId={groupId}&appKey={appKey}";
            Map<String, String> kv = new HashMap<String, String>();
            kv.put("groupId", String.valueOf(groupId));
            String result = zhuanApi.get(url, kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONArray data = jo.getJSONArray("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    list = gson.fromJson(data.toString(), new TypeToken<List<OrderTemp>>() {
                    }.getType());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public ServiceType queryServiceType(Long carTypeId, Long companyId, String serviceTypeStr) {
        ServiceType serviceType = new ServiceType();
        try {
            String url = zhuanApi.getZhuanBaseURL() + ZhuanApi.QUERY_SERVICE_TYPE
                + "?carTypeId={carTypeId}&companyId={companyId}&serviceType={serviceType}&appKey={appKey}";
            Map<String, String> kv = new HashMap<String, String>();
            kv.put("carTypeId", String.valueOf(carTypeId));
            kv.put("companyId", String.valueOf(companyId));
            kv.put("serviceType", serviceTypeStr);
            String result = zhuanApi.get(url, kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    serviceType = gson.fromJson(data.toString(), ServiceType.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serviceType;
    }

    @Override
    public Result<List<Order>> createOrderV4up(Long passengerId, String passengerName, String passengerPhone, Long companyId, String companyName,
        String startAddress, String startAddressDetail, Double startLat, Double startLng, String endAddress, String endAddressDetail,
        Double endLat, Double endLng, Date serverDate, String carTypes, String couponIds, String channelName, String operator,
        String serviceType, String memo, String flightNo, String trainNo, Integer travelTime, Double mileage, String createOrderName,
        Integer bookStatus, BigDecimal makePrice, Integer isMakePrice) {
        Result<List<Order>> r = new Result<List<Order>>();
        Passenger passenger = new Passenger();
        if (passengerId == null) {
            if (StringUtils.isNotBlank(passengerName)) {
                passenger.setName(passengerName);
            } else {
                passenger.setName("先生/女士");
            }
            passenger.setPhone(passengerPhone);
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_PHONE);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(startLng);
            passenger.setLatitude(startLat);
            passenger.setCompanyId(companyId);
            passenger.setCompanyName(companyName);
            try {
                Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());
                passenger = result.getResult();
                if (passenger.getId() == null || passenger.getId() == 0) {
                    r.setMessage("创建新乘客失败!");
                    r.setSuccess(false);
                    return r;
                }
            } catch (Exception e) {
                e.printStackTrace();
                r.setMessage("创建新乘客失败!");
                r.setSuccess(false);
                return r;
            }

        } else {
            Result<Passenger> result = passengerApi.findOnePassenger(passengerId, settingUtils.get());
            passenger = result.getResult();
        }
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("passengerId", String.valueOf(passenger.getId()));
        kv.add("passengerName", passenger.getName());
        kv.add("passengerPhone", passenger.getPhone());
        kv.add("userPhone", passenger.getPhone());
        kv.add("companyId", String.valueOf(companyId));
        kv.add("companyName", companyName);
        kv.add("channelName", channelName);
        kv.add("createOrderName", createOrderName);
        kv.add("serverTime", String.valueOf(serverDate.getTime()));
        kv.add("startAddress", startAddress);
        kv.add("makePrice", String.valueOf(makePrice));
        if (isMakePrice != null) {
            kv.add("isMakePrice", String.valueOf(isMakePrice));
        }

        if (StringUtils.isNotBlank(startAddressDetail)) {
            kv.add("startAddressDetail", startAddressDetail);
        }
        kv.add("startLat", String.valueOf(startLat));
        kv.add("startLng", String.valueOf(startLng));
        if (StringUtils.isNotBlank(endAddress) && endLat != null && endLng != null) {
            kv.add("endAddress", endAddress);
            kv.add("endLat", String.valueOf(endLat));
            kv.add("endLng", String.valueOf(endLng));
        }
        if (StringUtils.isNotBlank(endAddressDetail)) {
            kv.add("endAddressDetail", endAddressDetail);
        }
        kv.add("prePay", String.valueOf(false));
        kv.add("operator", operator);
        kv.add("carTypes", "[" + carTypes + "]");
        if (StringUtils.isNotBlank(couponIds)) {
            kv.add("couponIds", couponIds);
        }
        if (StringUtils.isNotBlank(memo)) {
            kv.add("memo", memo);
        }
        if (StringUtils.isNotBlank(flightNo) && serviceType.contains("ji")) {
            kv.add("flightNo", flightNo);
        }
        if (StringUtils.isNotBlank(trainNo) && serviceType.contains("zhan")) {
            kv.add("trainNo", trainNo);
        }
        kv.add("serviceType", serviceType);
        kv.add("bookStatus", String.valueOf(bookStatus));
        kv.add("travelTime", String.valueOf(travelTime));
        kv.add("mileage", String.valueOf(mileage));

        String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.CREATE_ORDER_V4UP, kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {

                JSONObject data = jo.getJSONObject("data");
                String orderIds = data.getString("orderIds");// order group

                String[] orderIdsStr = orderIds.split(",");
                List<Order> orderList = new ArrayList<Order>();
                for (int i = 0; i < orderIdsStr.length; i++) {
                    Long orderId = Long.valueOf(orderIdsStr[i]);
                    orderList.add(this.findOne(orderId));
                    // 推送至监管平台
                    superviceService.pushDdjs(this.findOne(orderId));
                }

                r.setResult(orderList);
                r.setSuccess(true);

            } else {
                String message = jo.getString("message");
                r.setMessage(message);
                r.setSuccess(false);
            }
        }
        return r;
    }

    @Override
    public Page<CarType> queryCarTypeV4up() {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        List<CarType> list = new ArrayList<CarType>();
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL());
        builder.append(ZhuanApi.QUERY_CARTYPE_V4UP);
        builder.append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));

        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());

        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray rows = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(rows.toString(), new TypeToken<List<CarType>>() {
                }.getType());
                total = data.getLong("total");
            }
        }
        return new PageImpl<CarType>(list, pageable, total);
    }

    @Override
    public Page<CarTypeCompany> queryCarTypeCompany(Long carTypeId, String companyName, Long companyId) {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        List<CarTypeCompany> list = new ArrayList<CarTypeCompany>();
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL());
        builder.append(ZhuanApi.QUERY_CARTYPECOMPANY_V4UP);
        builder.append("?carTypeId={carTypeId}&appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carTypeId", String.valueOf(carTypeId));
        if (!principal.isCompanyType()) {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            builder.append("&companyId={companyId}");
        }
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", companyName);
            builder.append("&companyName={companyName}");
        }
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));

        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());

        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray rows = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(rows.toString(), new TypeToken<List<CarTypeCompany>>() {
                }.getType());
                total = data.getLong("total");
            }
        }
        return new PageImpl<CarTypeCompany>(list, pageable, total);
    }

    @Override
    public Map<String, Object> deleteCarTypeCompany(Long carTypeCompanyId) {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.DELETE_CARTYPECOMPANY_V4UP)
            .append("?carTypeCompanyId={carTypeCompanyId}&appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carTypeCompanyId", String.valueOf(carTypeCompanyId));
        String result = zhuanApi.delete(builder.toString(), kv, settingUtils.get());
        if (StringUtils.isBlank(result)) {
            map.put("code", 0);
            map.put("message", "成功");
        } else {
            map.put("code", -1);
            map.put("message", "失败");
        }
        return map;
    }

    @Override
    public Car queryCarByNumber(String carNumber) {
        Car car = null;
        try {
            // 这里是拼接接口访问路径+参数
            String url = zhuanApi.getZhuanBaseURL() + ZhuanApi.QUERY_CAR_BY_NUMBER + "?carNumber={carNumber}&appKey={appKey}";
            Map<String, String> kv = new HashMap<String, String>();
            // 这里封装了车牌号
            kv.put("carNumber", carNumber);
            // 这里是实际访问api调用接口:url,车牌号,商店的配置信息
            String result = zhuanApi.get(url, kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    Object object = jo.get("data");
                    if (null != object) {
                        Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                        car = gson.fromJson(object.toString(), Car.class);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return car;
    }

    @Override
    public Page<Insurance> queryInsuranceByPage(Long carId) {
        Pageable pageable = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.CAR_INSURANCE_PAGE).append("?appKey={appKey}&carId={carId}");
        Integer limit = Pager.getLimit();
        Integer page = Pager.getPage();
        Map<String, String> kv = new HashMap<String, String>();
        if (page != null && limit != null) {
            kv.put("page", String.valueOf(page + 1));
            kv.put("rows", String.valueOf(limit));
            builder.append("&page={page}&rows={rows}");
            pageable = new PageRequest(page, limit);
        }
        kv.put("carId", carId + "");

        List<Insurance> list = new ArrayList<Insurance>();
        ;
        String result = zhuanApi.get(builder.toString(), kv, settingUtils.get());
        int total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                total = data.getInt("total");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Insurance>>() {
                }.getType());
            }
        }
        return new PageImpl<Insurance>(list, pageable, total);
    }

    @Override
    public void deletetInsurance(Long id) {
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.DELETET_INSURANCE, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        if (jo.optInt("code", -1) == 0) {
            try {
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                Insurance insurance = gson
                    .fromJson(jo.getJSONObject("data").toString(), Insurance.class);
                Car obj = this.findCar(insurance.getCarId());
                ClbxMessage clbx = new ClbxMessage();
                clbx.setCertificateNo(obj.getTaxiNo());
                clbx.setVehicleLicense(obj.getCarNumber());
                clbx.setInsuranceEndDate(insurance.getInsuranceEndDate());
                clbx.setInsuranceValidDate(insurance.getInsuranceValidDate());
                clbx.setInsuranceAmount(new BigDecimal(insurance.getInsuranceAmount()).setScale(BigDecimal.ROUND_HALF_UP, 2).doubleValue());
                clbx.setInsuranceType(insurance.getInsuranceType());
                clbx.setInsuranceCode(insurance.getInsuranceCode());
                clbx.setInsuranceCompany(insurance.getInsuranceCompany());
                clbx.setCertificateNo(insurance.getCertificateNo());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Map<String, Object> createInsurance(Insurance insurance) {
        Map<String, Object> map = new HashMap<String, Object>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("carId", String.valueOf(insurance.getCarId()));

        if (StringUtils.isNotBlank(insurance.getInsuranceCompany())) {
            kv.add("insuranceCompany", String.valueOf(insurance.getInsuranceCompany()));
        }
        if (insurance.getInsuranceValidDate() != null) {
            kv.add("insuranceValidDate", String.valueOf(insurance.getInsuranceValidDate().getTime()));
        }
        if (insurance.getInsuranceEndDate() != null) {
            kv.add("insuranceEndDate", String.valueOf(insurance.getInsyranceEndDate().getTime()));
        }
        if (StringUtils.isNotBlank(insurance.getInsuranceCode())) {
            kv.add("insuranceCode", insurance.getInsuranceCode());
        }
        if (StringUtils.isNotBlank(insurance.getInsuranceType())) {
            kv.add("insuranceType", insurance.getInsuranceType());
        }
        if (insurance.getInsuranceAmount() != null) {
            kv.add("insuranceAmount", String.valueOf(insurance.getInsuranceAmount()));
        }
        if (StringUtils.isNotBlank(insurance.getVehicleLicense())) {
            kv.add("vehicleLicense", insurance.getVehicleLicense());
        }
        if (StringUtils.isNotBlank(insurance.getCertificateNo())) {
            kv.add("certificateNo", insurance.getCertificateNo());
        }
        String result = zhuanApi.postMultiValueMap(zhuanApi.getZhuanBaseURL() + ZhuanApi.CAR_INSURANCE, kv, settingUtils.get());

        if (!StringUtils.isBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                map.put("success", true);
                map.put("code", 0);
                map.put("message", "成功");
                try {
                    /*
                     * Car obj = this.findCar(insurance.getCarId()); ClbxMessage
                     * clbx = new ClbxMessage();
                     * clbx.setCertificateNo(obj.getTaxiNo());
                     * clbx.setVehicleLicense(obj.getCarNumber());
                     * clbx.setInsuranceEndDate
                     * (insurance.getInsuranceEndDate());
                     * clbx.setInsuranceValidDate
                     * (insurance.getInsuranceValidDate());
                     * clbx.setInsuranceAmount(
                     * String.format("%.2f",insurance.getInsuranceAmount()));
                     * clbx.setInsuranceType(insurance.getInsuranceType());
                     * clbx.setInsuranceCode(insurance.getInsuranceCode());
                     * clbx.
                     * setInsuranceCompany(insurance.getInsuranceCompany());
                     * clbx.setFlag(1);
                     */
                    ClbxMessage clbx = new ClbxMessage();
                    Car car = this.findCar(insurance.getCarId());

                    // A.4.8. 车辆保险信息接口begin
                    // CompanyId:公司标识
                    // VehicleNo:车辆号牌
                    clbx.setVehicleLicense(car.getCarNumber());
                    // InsurCom:保险公司名称
                    clbx.setInsuranceCompany(insurance.getInsuranceCompany());
                    // InsurNum:保险号
                    // clbx.setCertificateNo(insurance.getCertificateNo());
                    clbx.setInsuranceCode(insurance.getInsuranceCode());
                    // InsurType:保险类型
                    clbx.setInsuranceType(insurance.getInsuranceType());
                    // InsurCount:保险金额,数字型
                    clbx.setInsuranceAmount(new BigDecimal(insurance.getInsuranceAmount()).setScale(BigDecimal.ROUND_HALF_UP, 2).doubleValue());
                    // InsurEff:保险生效时间,数字型,YYYYMMDD
                    clbx.setInsuranceValidDate(insurance.getInsuranceValidDate());
                    // InsurExp:保险到期时间,数字型,YYYYMMDD
                    clbx.setInsuranceEndDate(insurance.getInsuranceEndDate());
                    // 网约车车辆运输证号
                    clbx.setCertificateNo(car.getTaxiNo());
                    // frameNo:车架号
                    clbx.setFrameNo(car.getVin());
                    // Flag:操作标识,数字型,1：新增2：更新3：删除
                    // UpdateTime:更新时间,数字型,YYYYMMDDhhmmss
                    // A.4.8. 车辆保险信息接口end
                    superviceService.ClbxMessage(clbx);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                map.put("success", false);
                map.put("code", -1);
                map.put("message", "失败");
            }

        } else {
            map.put("code", -1);
            map.put("message", "失败");
        }
        return map;
    }

    @Override
    public Map<String, Object> upCarInfo(Long[] ids, String basePath) {
        try {
            Page<Car> temp = this.findCarByIds(ids, null, null);
            // 上传监管平台
            final List<Car> content = temp.getContent();
            final String threadBasePath = basePath;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (Car obj : content) {
                        obj.setFlag(1);
                        superviceService.ClbaMessage(obj, threadBasePath);
                    }
                }
            }).start();
            Map<String, Object> resp = new HashMap<>();
            resp.put("code", 0);
            resp.put("message", "成功");
            return resp;

        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> resp = new HashMap<>();
            resp.put("code", 500);
            resp.put("message", "失败");
            return resp;
        }
    }

    @Override
    public Map<String, Object> countOnDutyByDriver(Long driverId, Date lastTime, Date end) {
        try {
            Map<String, String> kv = new HashMap<>();
            StringBuilder sb = new StringBuilder(zhuanApi.getZhuanBaseURL() + ZhuanApi.COUNT_ONDUTYBY_DRIVER);
            sb.append("?appKey={appKey}").append("&driverId={driverId}&startTime={startTime}&endTime={endTime}");
            kv.put("driverId", driverId + "");
            kv.put("startTime", lastTime.getTime() + "");
            kv.put("endTime", end.getTime() + "");
            String resultStr = zhuanApi.get(sb.toString(), kv, settingUtils.get());
            JSONObject json = new JSONObject(resultStr);
            if (json.optInt("code", -1) == 0) {
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                Map<String, Object> data = gson.fromJson(json.get("data").toString(), Map.class);
                return data;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void updateUpStatus(Long id) {
        try {
            MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

            kv.add("id", String.valueOf(id));
            String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() + ZhuanApi.UPDATE_UP_STATUS, kv, settingUtils.get());
            // String result = zhuanApi.post(zhuanApi.getZhuanBaseURL() +
            // ZhuanApi.UPDATE_CARTYPE_COMPANY, kv, settingUtils.get());

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    @Override
    public Car getCarByNumberAndFlights(String carNumber, String flights) {
        Car car = null;
        try {
            String url = zhuanApi.getZhuanBaseURL() + ZhuanApi.QUERY_CAR_BY_NUMBER_AND_FLIGHTS
                + "?carNumber={carNumber}&appKey={appKey}&flights={flights}";
            Map<String, String> kv = new HashMap<String, String>();
            kv.put("carNumber", carNumber);
            kv.put("flights", flights);
            String result = zhuanApi.get(url, kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    Object object = jo.get("data");
                    if (null != object) {
                        Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                        car = gson.fromJson(object.toString(), Car.class);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return car;
    }

    @Override
    public List<CarTypeRel> findCarTypeRelByCarTypeId(Long carTypeId) {
        List<CarTypeRel> carTypeList = new ArrayList<CarTypeRel>();
        try {
            String url = zhuanApi.getZhuanBaseURL() + ZhuanApi.QUERY_CAR_TYPE_REL + "?carTypeId={carTypeId}&appKey={appKey}";
            Map<String, String> kv = new HashMap<String, String>();
            kv.put("carTypeId", carTypeId.toString());
            String result = zhuanApi.get(url, kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONArray data = jo.getJSONArray("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    carTypeList = gson.fromJson(data.toString(), new TypeToken<List<CarTypeRel>>() {
                    }.getType());
                    return carTypeList;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return carTypeList;
    }

    @Override
    public CarType getCarTypeByTypeName(String typeName) {
        CarType carType = null;
        try {
            String url = zhuanApi.getZhuanBaseURL() + ZhuanApi.QUERY_CARTYPE_BY_CARTYPENAME + "?typeName={typeName}&appKey={appKey}";
            Map<String, String> kv = new HashMap<String, String>();
            kv.put("typeName", typeName);
            String result = zhuanApi.get(url, kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    Object object = jo.get("data");
                    if (null != object) {
                        Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                        carType = gson.fromJson(object.toString(), CarType.class);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return carType;
    }


    @Override
    public List<CarType> getCarTypeByIftaxi(String ifTaxi) {
        List<CarType> carTypeList = new ArrayList<CarType>();
        try {
            String url = zhuanApi.getZhuanBaseURL() + ZhuanApi.QUERY_CARTYPE_BY_IFTAXI + "?ifTaxi={ifTaxi}&appKey={appKey}";
            Map<String, String> kv = new HashMap<String, String>();
            kv.put("ifTaxi", ifTaxi);
            String result = zhuanApi.get(url, kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONArray data = jo.getJSONArray("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    carTypeList = gson.fromJson(data.toString(), new TypeToken<List<CarType>>() {
                    }.getType());
                    return carTypeList;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return carTypeList;
    }

    @Override
    public Result<Order> autoCallback(Order order, Driver driver) {

        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanApi.getZhuanBaseURL()).append(ZhuanApi.CALLBACK).append("?appKey={appKey}");
        sb.append("&orderId={orderId}");
        sb.append("&action={action}");
        sb.append("&operator={operator}");
        sb.append("&cause={cause}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("action", "callback");
        kv.put("cause", "时间逾期，系统自动收回了该订单");
        kv.put("operator", "系统");

        String resultStr = zhuanApi.put(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {

            if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ONLINE, null, driver.getId());
            }

            result.setSuccess(true);
        }

        return result;
    }

    /**
     * 查询不能接预约订单的司机
     */
    @Override
    public Set<String> findBookDrivers() {
        Setting setting = settingUtils.get();
        Integer yuYueTime = setting.getZhuanYuyueTime();
        Integer yuYueMax = setting.getZhuanYuyueMax();
        Set<String> set = new HashSet<String>();
        if (yuYueTime != null && yuYueMax != null && yuYueTime == 0 && yuYueMax == 0) {
            return set;
        }
        if (yuYueTime == null && yuYueMax == null) {
            return set;
        }
        //获取能够接预约订单的司机
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL() + ZhuanApi.COUNT_BOOK_DRIVER + "?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (yuYueMax != null && yuYueMax != 0) {
            kv.put("zhuanYuyueMax", String.valueOf(setting.getZhuanYuyueMax()));
            builder.append("&zhuanYuyueMax={zhuanYuyueMax}");
        }
        if (yuYueTime != null && yuYueTime != 0) {
            Long date = System.currentTimeMillis() / 1000;
            Long zhuanYuyueTime = date + (yuYueTime.longValue() * 60);
            kv.put("zhuanYuyueTime", String.valueOf(zhuanYuyueTime));
            builder.append("&zhuanYuyueTime={zhuanYuyueTime}");
        }
        //获取能够接预约订单的司机结果集
        String result = zhuanApi.get(builder.toString(), kv, setting);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Map<String, Object>>>() {
                }.getType());
            }
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    set.add(list.get(i).get("employId").toString());
                }
            }
        }
        return set;
    }

    /**
     * 获取所有订单都不能接的司机
     */
    @Override
    public Set<String> findBusyBookDrivers() {
        Setting setting = settingUtils.get();
        Integer yuYueTime = setting.getZhuanYuyueTime();
        Set<String> set = new HashSet<String>();
        if (yuYueTime != null && yuYueTime == 0) {
            return set;
        }
        if (yuYueTime == null) {
            return set;
        }
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL() + ZhuanApi.COUNT_BUSY_BOOK_DRIVER + "?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        Long date = System.currentTimeMillis() / 1000;
        Long zhuanYuyueTime = date + (yuYueTime.longValue() * 60);
        kv.put("zhuanYuyueTime", String.valueOf(zhuanYuyueTime));
        builder.append("&zhuanYuyueTime={zhuanYuyueTime}");
        String result = zhuanApi.get(builder.toString(), kv, setting);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Map<String, Object>>>() {
                }.getType());
            }
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    set.add(list.get(i).get("employId").toString());
                }
            }
        }
        return set;
    }

    @Override
    public Boolean findDriverBusy(Long employId, Integer isBook, Long orderId) {
        Setting setting = settingUtils.get();
        Integer yuYueTime = setting.getZhuanYuyueTime();
        Integer yuYueMax = setting.getZhuanYuyueMax();
        Set<String> set = new HashSet<String>();
        if (yuYueTime != null && yuYueMax != null && yuYueTime == 0 && yuYueMax == 0) {
            return true;
        }
        if (yuYueTime == null && yuYueMax == null) {
            return true;
        }
        //获取能够接预约订单的司机
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanApi.getZhuanBaseURL() + ZhuanApi.FIND_DREIVER_BUSY + "?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("employId", String.valueOf(employId));
        builder.append("&employId={employId}");
        if (yuYueMax != null && yuYueMax != 0 && isBook == 1) {
            kv.put("zhuanYuyueMax", String.valueOf(setting.getZhuanYuyueMax()));
            builder.append("&zhuanYuyueMax={zhuanYuyueMax}");
        }
        if (yuYueTime != null && yuYueTime != 0) {
            Long date = System.currentTimeMillis() / 1000;
            Long zhuanYuyueTime = date + (yuYueTime.longValue() * 60);
            kv.put("zhuanYuyueTime", String.valueOf(zhuanYuyueTime));
            builder.append("&zhuanYuyueTime={zhuanYuyueTime}");
        }
        kv.put("orderId", String.valueOf(orderId));
        builder.append("&orderId={orderId}");
        //获取能够接预约订单的司机结果集
        String result = zhuanApi.get(builder.toString(), kv, setting);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }


}
